指定复制构造函数不用作复制构造函数

Specify copy constructor to not be used as copy constructor

我有一个class A。在这个class中它包含一个指向另一个A的指针。

class A
{
    A* sub = NULL;
};

我想要一个默认此指针为 NULL 的空构造函数,以及另一个传递 pointer/reference 的构造函数。第二个构造函数会将参数复制到 new A() 对象中,并将 sub 从参数传输到自身。
class 现在:

class A
{
    A* sub = NULL
    A(A* source)
    {
        this->sub = new A(*source);//copy the source 'A'

        // we now have a copy of "source" and all of its children
        // but to prevent the "source" from deleting our new
        // children (destructor deletes children recursively),
        // "source"s children are disconnected from "source"
        source->sub = NULL;

        // this invalidates sub, but that is desired for my class
    }
}

到目前为止,这没有问题。相反,问题是我想让 "source" 变量成为参考。现在这是一个问题,因为这会使构造函数具有复制构造函数的签名。

有没有办法告诉编译器不应该将其视为复制构造函数?如果这是可能的,甚至应该这样做吗?

您要实现的目标称为 move constructor。特别是,这种确切的行为是通过使用 std::unique_ptr.

实现的