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;
    }
};

最佳答案

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
};

然后将您的类(class)声明为
struct Type
{
    int a;
    double b;
    bool c;
    // ... a lot of basic members
    DynInt p;
};

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

07-24 21:45