Skip to content

Instantly share code, notes, and snippets.

@thynson
Last active August 29, 2015 13:56
Show Gist options
  • Save thynson/8996642 to your computer and use it in GitHub Desktop.
Save thynson/8996642 to your computer and use it in GitHub Desktop.
#include <string>
struct A
{
// You need to explicitly define constructor and destructor
union
{
std::string a;
int b;
};
int state;
A(std::string x)
: a(std::move(x))
, state(1)
{ }
A(int x)
: b(x)
, state(0)
{ }
~A()
{
if (state) a.std::string::~string(); // Manually call destructor of std::string
}
};
int main()
{
A a(1);
A b("hello world");
}
@thynson
Copy link
Author

thynson commented Feb 14, 2014

clang++编译错误
string_inside_union.cpp:30:16: error: expected unqualified-id
if (state) a.(std::string::~string)(); // Manually call destructor of std::string

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