Skip to content

Instantly share code, notes, and snippets.

@heimskr
Created February 6, 2020 04:54
Show Gist options
  • Save heimskr/00cbd3690e23f0715d41c85aa173647c to your computer and use it in GitHub Desktop.
Save heimskr/00cbd3690e23f0715d41c85aa173647c to your computer and use it in GitHub Desktop.
Demonstrates strange behavior of std::optional
#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
}
@heimskr
Copy link
Author

heimskr commented Feb 6, 2020

Sample output for both clang++ and g++:

() @ 0x7ffee6942580
() @ 0x7ffee6942548

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment