Created
February 6, 2020 04:54
-
-
Save heimskr/00cbd3690e23f0715d41c85aa173647c to your computer and use it in GitHub Desktop.
Demonstrates strange behavior of std::optional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <optional> | |
#include <string> | |
struct Delete { | |
std::string str = "delete"; | |
Delete() = delete; | |
Delete(const Delete &) = delete; | |
Delete(Delete &&) = delete; | |
Delete(const std::string &str_): str(str_) { | |
std::cout << "Constructing Delete(\"" << str_ << "\")\n"; | |
} | |
}; | |
struct Default { | |
std::string str = "default"; | |
Default() { | |
std::cout << "Constructing Default()\n"; | |
} | |
Default(const Default &) = delete; | |
Default(Default &&) = delete; | |
Default(const std::string &str_): str(str_) { | |
std::cout << "Constructing Default(\"" << str_ << "\")\n"; | |
} | |
}; | |
int main() { | |
std::optional<Delete> delete_opt; | |
Delete &del = *delete_opt; // No error | |
std::cout << "(" << del.str << ") @ " << &del << "\n"; // Empty | |
std::optional<Default> default_opt; | |
Default &def = *default_opt; // Silent | |
std::cout << "(" << def.str << ") @ " << &def << "\n"; // Empty | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output for both clang++ and g++: