扩展默认复制构造函数

时间:2014-07-29 19:37:09

标签: c++ c++11 copy-constructor

struct/class的复制构造函数中,如果打算复制一个,我怎么能避免逐个复制所有基本(intdouble等)成员指针成功?在这种意义上是否可以扩展默认的复制构造函数?

struct Type
{
    int a;
    double b;
    bool c;
    // ... a lot of basic members
    int* p;

    Type()
    {
        p = new int;
        *p = 0;
    }

    Type (const Type& t)
    {
        // how to avoid copying these members one by one
        this.a = t.a;
        this.b = t.b;
        this.c = t.c;

        // but only add this portion
        this.p = new int;
        *this.p = *t.p;
    }
};

1 个答案:

答案 0 :(得分:4)

为允许复制/移动的int *数据成员创建RAII包装器。

struct DynInt
{
    std::unique_ptr<int> p;

    DynInt() : DynInt(0) {}
    explicit DynInt(int i) : p(new int(i)) {}
    DynInt(DynInt const &other) : p(new int(*other.p)) {}
    DynInt& operator=(DynInt const& other)
    {
        *p = *other.p;
        return *this;
    }
    DynInt(DynInt&&) = default;
    DynInt& operator=(DynInt&&) = default;

    // maybe define operator* to allow direct access to *p
};

然后将您的班级声明为

struct Type
{
    int a;
    double b;
    bool c;
    // ... a lot of basic members
    DynInt p;
};

现在,隐式生成的复制构造函数将做正确的事情。