gpt4 book ai didi

c++ - 为类编写复制构造函数会在析构函数中删除对象时发生意外崩溃

转载 作者:行者123 更新时间:2023-11-28 02:55:26 24 4
gpt4 key购买 nike

为类编写复制构造函数会在析构函数中删除对象时发生意外崩溃。请参阅以下代码:

class ordinaryClass  // Sample class is used in Foo class
{
public:
ordinaryClass(){}
};

class Foo
{
public:
Foo():_ordinarayClass(0)
{
_ordinarayClass = new ordinaryClass();
}

~Foo()
{
delete _ordinarayClass; // the program crashes here when copy constructor is called.
}

Foo(const Foo &obj) // copy constructor
{
*_ordinarayClass = *obj._ordinarayClass;
}

Foo& operator=(const Foo& other) // copy assignment
{
*_ordinarayClass = *other._ordinarayClass;
return *this;
}

ordinaryClass *_ordinarayClass;
};

总的来说,如果我写这些代码:

Foo container2;
Foo container;
container = container2;

程序正常运行,正常退出。但是如果我这样写:

Foo container2;
Foo container = container2;

程序在退出时崩溃。我发现程序在 Foo 类的析构函数处崩溃。我在复制构造函数中犯了什么错误吗?非常感谢。

最佳答案

您需要的对象。不要只是复制指针。我将保留“你应该为此使用智能指针”的演讲,因为在这个网站上花费的任何时间都会让你在短期内在眼睑上留下纹身(顺便说一句,你应该使用智能指针 =P)

class Foo
{
public:
Foo() : _ordinaryClass(new ordinaryClass())
{
}

virtual ~Foo()
{
delete _ordinaryClass;
}

Foo(const Foo &obj) : _ordinaryClass(new ordinaryClass(*obj._ordinaryClass))
{
}

// copy/swap idiom for assignment. the value-parameter is
// intentional. think about what it does (hint: copy-ctor)
Foo& operator=(Foo other)
{
this->swap(other);
return *this;
}

private:
ordinaryClass *_ordinaryClass;

// they get our cruft, we get theirs.
void swap(Foo& other)
{
std::swap(_ordinaryClass, other._ordinaryClass);
}
};

顺便说一句,我会认真地重新考虑该成员是否应该首先是动态的。

关于c++ - 为类编写复制构造函数会在析构函数中删除对象时发生意外崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22125405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com