c++ - 如何为具有内部放置 new 的类实现安全复制构造函数(使用 std::string)

标签 c++ copy-constructor stdstring placement-new reinterpret-cast

这是我的代码:

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 的情况的建议,我们将不胜感激。

最佳答案

我不确定你所做的是否是一个好的设计,但是为了回答你关于 placement-new 的问题:你像在任何其他 new 表达式中一样提供构造函数参数:

构造新字符串:

typedef std::basic_string<unsigned char> ustring;

RS_Token(const char* pstr)
{
  void * p = static_cast<void*>(array);
  new (p) ustring(pstr, pstr + std::strlen(pstr));
}

复制构造:

RS_Token(const RS_Token & other)
{
  void * p = static_cast<void*>(array);
  new (p) ustring(*reinterpret_cast<const ustring *>(other.array));
}

分配:

RS_Token & operator=(const RS_Token & other)
{
  ustring & s = *reinterpret_cast<ustring *>(array);
  s = *reinterpret_cast<const ustring *>(other.array);
  return this;
}

关于c++ - 如何为具有内部放置 new 的类实现安全复制构造函数(使用 std::string),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7039006/

相关文章:

c++ - 在 C++ 中进行基本 128 位整数计算的有效方法?

c++ - 包含在 main 方法中抛出错误的类对象的 vector

C++递归地生成集合的排列

c++ - 什么是三法则?

c++ - VC++2010 似乎只在固定数组中分配一个 std::string

c++ - 从 std::string 中提取信息

c++ - 我可以在设置期望后复制一个谷歌模拟对象吗?

c++ - 为什么赋值运算符重载会创建一个对象的拷贝?

c++ - 复制构造函数和链接错误

c++ - 大写字母