我正在嘗試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)