我正在尝试C++自己,我真的变得有点困惑。
我真的有理解构造/复制构造/移动构造/析构的问题,并正确设置它们。C++ - 构造函数,复制构造函数,移动构造函数,析构函数
我想实现一个副本以及移动构造函数和析构函数到class Container
。我首先尝试了复制构造函数,并认为我是正确的。不幸的是,当试图执行delete[] data
时,析构函数让程序在最后崩溃。 我觉得我之前有一些错误,data
不在那里了,我复制了它错误或任何其他。我希望你能帮助我并理解我的错误。 我也尝试过一个移动构造函数(下面),这绝对不起作用。
感谢您的帮助球员。希望能够对:)
容器类后回馈:
#include <iostream>
#include <memory>
class Container
{
public:
Container()
{
length = 0;
data = nullptr;
}
Container(int lengthin):Container()
{
length = lengthin;
data = new double[lengthin];
//data[lengthin];
//double data[lengthin] = {0};
}
Container(std::initializer_list<double> listin)
:Container((int)listin.size())
{
std::uninitialized_copy (listin.begin(), listin.end(), data);
}
//copy constructor - working?
Container(const Container& other):Container(other.length)
{
//data = other.data;
//length = other.length;
for (auto i=0; i<other.length; i++)
{
data[i] = other.data[i];
}
}
//~Container(){length = 0;}
~Container()
{
delete[] data;
length = 0;
}
Container operator+(Container cin)
{
Container cout(cin.length);
cout.length = cin.length;
for (auto i=0; i<cin.length; i++)
{
cout.data[i] = cin.data[i] + data[i];
}
return cout;
}
Container operator-(Container cin)
{
Container cout(cin.length);
cout.length = cin.length;
for (auto i=0; i<cin.length; i++)
{
cout.data[i] = data[i]-cin.data[i];
}
return cout;
}
void print(const std::string &info) const
{
// print the address of this instance, the attributes `length` and
// `data` and the `info` string
std::cout << " " << this << " " << length << " " << data << " "
<< info << std::endl;
}
private:
int length;
double *data;
};
主程序:
int main()
{
Container a({ 1, 2, 3 });
std::cout << " a has address " << &a << std::endl;
Container b = { 4, 5, 6 };
std::cout << " b has address " << &b << std::endl;
Container c(a);
std::cout << " c has address " << &c << std::endl;
Container d = a + b;
std::cout << " d has address " << &d << std::endl;
Container e;
std::cout << " e has address " << &e << std::endl;
e = a + b;
//Container f(std::move(a + b));
//std::cout << " f has address " << &f << std::endl;
return 0;}
而试图转移构造函数:
Container(const Container&& other):length(other.length), data(other.data)