R
REH
Hi. I want to have a union that contained various types, some of which are
classes with constructors. I'm attempting to acheive this with placement
new. Please tell me if the following code snippet meets the current
standard. Should I cast char* to void* before casting to std::string*?
Regards,
REH
class entry {
public:
enum entry_type {
none, str
};
entry() : m_type(none) {}
entry(const std::string& s) : m_type(str) {new(m_data.str)
std::string(s);}
// note: my compiler didn't like the use of std::string below.
// it would only accept using a typedef of std::string or a using
clause.
// specifically, it didn't like the ~string(). why?
~entry() {using std::string; if (m_type == str)
reinterpret_cast<string*>(m_data.str)->~string();}
entry_type get_type() const {return m_type;}
std::string get_str() const
{
if (m_type == str)
*reinterpret_cast<string*>(m_data.str);
else
throw format_error(); // defined elsewhere
}
private:
entry_type m_type;
union {
double dbl; // ensure any necessary alignment of types
char str[sizeof(std::string)];
} m_data;
};
classes with constructors. I'm attempting to acheive this with placement
new. Please tell me if the following code snippet meets the current
standard. Should I cast char* to void* before casting to std::string*?
Regards,
REH
class entry {
public:
enum entry_type {
none, str
};
entry() : m_type(none) {}
entry(const std::string& s) : m_type(str) {new(m_data.str)
std::string(s);}
// note: my compiler didn't like the use of std::string below.
// it would only accept using a typedef of std::string or a using
clause.
// specifically, it didn't like the ~string(). why?
~entry() {using std::string; if (m_type == str)
reinterpret_cast<string*>(m_data.str)->~string();}
entry_type get_type() const {return m_type;}
std::string get_str() const
{
if (m_type == str)
*reinterpret_cast<string*>(m_data.str);
else
throw format_error(); // defined elsewhere
}
private:
entry_type m_type;
union {
double dbl; // ensure any necessary alignment of types
char str[sizeof(std::string)];
} m_data;
};