复制构造函数以进行非动态分配

Vit*_*one 2 c++

根据定义:当复制此类的对象时,复制指针成员,但不复制指向的缓冲区,导致两个对象指向同一个, 因此我们使用复制构造函数.
但在下面的类中没有复制构造函数,但它工作!为什么?为什么我不需要深度复制?

class Human
{
private:
    int* aValue;

public:
    Human(int* param)
    {
        aValue=param;
    }

    void ShowInfos()
    {
        cout<<"Human's info:"<<*aValue<<endl;
    }
};

void JustAFunction(Human m)
{
    m.ShowInfos();
}

int main()
{
    int age = 10;
    Human aHuman(&age);
    aHuman.ShowInfos();
    JustAFunction(aHuman);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


输出:

人类信息:10
人类信息:10

Luc*_*ore 6

当您的类拥有资源时,复制构造函数很有用.在你的情况下,它没有 - 它既不创建也不删除aValue自己.

如果你这样做了,说:

Human()
{
    aValue=new int;
}
Run Code Online (Sandbox Code Playgroud)

并妥善清理内存:

~Human()
{
    delete aValue;
}
Run Code Online (Sandbox Code Playgroud)

然后你会遇到问题,因为Human a;并且Human b(a);会让成员aValue指向同一个位置,当它们超出范围时,会释放相同的内存,从而导致双重删除.