Skip to content

Instantly share code, notes, and snippets.

@taegyunkim
Last active May 12, 2025 19:33
Show Gist options
  • Save taegyunkim/9191e643e315be55e78e383ccc498713 to your computer and use it in GitHub Desktop.
Save taegyunkim/9191e643e315be55e78e383ccc498713 to your computer and use it in GitHub Desktop.
c++ variant
#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
#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