Is it correct to use std::string
(or other non trivial types) with int
(or other trivial and non trivial types) inside the same union?
I am already implemented it like this:
#include <iostream>
#include <string>
struct Foo
{
enum Type {data_string, data_int};
int m_type;
Foo(Type t) : m_type(t)
{
if (t == Type::data_string) {
new (&s) std::string();
}
}
~Foo()
{
if (m_type == Type::data_string) {
s.~basic_string();
}
}
union
{
int n;
std::string s;
};
};
int main()
{
Foo f1(Foo::Type::data_string);
f1.s = "hello ";
std::cout << f1.s;
Foo f2(Foo::Type::data_int);
f2.n = 100;
std::cout << f2.n;
}
and it works pretty good. But i am not sure about this code. Is it correct code from the C++ standard perspective?
2