Last active
May 12, 2025 19:33
-
-
Save taegyunkim/9191e643e315be55e78e383ccc498713 to your computer and use it in GitHub Desktop.
c++ variant
This file contains hidden or 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 <variant> | |
#include <cstdio> | |
struct Thing { | |
Thing() { | |
std::printf("default constructor\n"); | |
} | |
Thing(Thing &&other) { | |
std::printf("move constructor\n"); | |
} | |
~Thing() { | |
std::printf("destructor\n"); | |
} | |
}; | |
std::variant<Thing, int> new_thing() { | |
return Thing{}; | |
} | |
int main () | |
{ | |
auto v = new_thing(); | |
std::printf("after new\n"); | |
} | |
// Outputs when compiled with C++17 -O0 on cpp.sh | |
// default constructor | |
// move constructor | |
// destructor | |
// after new | |
// destructor |
This file contains hidden or 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 <variant> | |
#include <cstdio> | |
struct Thing { | |
Thing() { | |
std::printf("default constructor\n"); | |
} | |
Thing(Thing &&other) { | |
std::printf("move constructor\n"); | |
} | |
~Thing() { | |
std::printf("destructor\n"); | |
} | |
}; | |
std::variant<Thing, int> new_thing() { | |
return std::variant<Thing, int>{std::in_place_type<Thing>}; | |
} | |
int main () | |
{ | |
auto v = new_thing(); | |
std::printf("after new\n"); | |
} | |
// Outputs when compiled with C++17 -O0 on cpp.sh | |
// default constructor | |
// after new | |
// destructor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment