這裏是我的代碼:如何實現對於具有內部放置新的(用的std :: string)類安全拷貝構造函數
struct RS_Token
{
char id;
char cleanup;
unsigned char array[sizeof (std::string) > sizeof (double) ? sizeof (std::string) : sizeof (double)];
RS_Token(int a) :
id(a),
cleanup(0)
{
}
RS_Token(int a, const char* pstr) : // identifier or text
id(a),
cleanup(1)
{
new (array) std::basic_string<unsigned char>((unsigned char*)pstr);
}
RS_Token(int a, int b) : // integer
id(a),
cleanup(0)
{
new (array) int(b);
}
RS_Token(int a, double b) : // float (double)
id(a),
cleanup(0)
{
new (array) double(b);
}
~RS_Token()
{
if (cleanup)
{
std::basic_string<unsigned char>* p = reinterpret_cast<std::basic_string<unsigned char>*>(array);
p->~basic_string();
}
}
};
如何添加一個拷貝構造函數,妥善處理的情況下任何建議,其中一個std :: string已被內部分配,將不勝感激。
出了什麼問題使獨立'的std :: string'和'double'變量?您擁有的代碼將會出現[嚴重對齊問題](http://www.gotw.ca/gotw/028.htm)等等。如果你讓它們成爲獨立的成員變量,編譯器生成的拷貝構造函數將爲你做正確的事情。 –
Placement-new通常會有一個'void *'的參數,所以你可以把那些乏味的演員都放在一邊。 –
可能'boost :: variant'會處理這些事情。 –
visitor