gpt4 book ai didi

c++ - 如何避免复制赋值运算符的双重释放或损坏(fasttop)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:16:43 25 4
gpt4 key购买 nike

我有以下类,我在其中强制编译器生成所有复制/移动构造函数和赋值运算符。

class foo {
public:
float *x;
size_t size;
foo(int m){
size = m;
x = new float[size];}

foo(const foo&) = default;
foo(foo&&) = default;
foo& operator =(const foo&) = default;
foo& operator =(foo&&) = default;

~foo(){delete [] x;}

void fill(const float& num)
{
std::fill(x,x+size,num);
}

void print()
{
for (auto i=0;i<size;++i)
cout << x[i] << endl;
cout << endl;
}
};

然后我从 main 函数中调用它,就像这样

int main()
{
foo x(2);
x.fill(6);
x.print();


foo y(2);
y = x; // causes the error

return x;
}

现在我知道我通过分配 y = x 来释放内存两次;所以一旦一个被释放,另一个就是 null,我说得对吗?我继续实现我自己的复制赋值运算符

foo& operator=(const foo& other)
{
if (other.x!=x)
x = other.x;
return *this;
}

但是,我再次猜测我正在做默认构造函数正在做的事情。我的问题是如何制作一个正确的复制赋值运算符,这样这个问题就不会发生?

最佳答案

您需要复制的不是指针,而是指针的内容。一个好的使用方法是 copy and swap idiom因为你的复制构造函数应该已经完成​​了复制 x 的内容的工作:

friend void swap(foo& first, foo& second)
{
using std::swap;
swap(first.x, second.x);
swap(first.size, second.size);
}

foo& operator=(foo other) // note pass by value
{
swap(*this, other);
return *this;
}

关于c++ - 如何避免复制赋值运算符的双重释放或损坏(fasttop)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32637950/

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