【发布时间】:2020-01-26 13:58:45
【问题描述】:
我有以下类,它简单地包装了一个数组,并用构造函数向它添加了一些元素:
class myArray {
public:
myArray();
myArray(int a, int b);
myArray(int a, int b, int c);
myArray(myArray&& emplace);
~myArray();
int& operator [](int id);
private:
int *data;
};
myArray::myArray() {
data = new int[1];
data[0] = 0;
}
myArray::myArray(int a, int b) {
data = new int[3];
data[0] = 0;
data[1] = a;
data[2] = b;
}
myArray::myArray(int a, int b, int c) {
data = new int[4];
data[0] = 0;
data[1] = a;
data[2] = b;
data[3] = c;
}
myArray::~myArray() {
std::cout << "Destructor"<<std::endl;
delete[] data;
}
int& myArray::operator [](int id) {
return data[id];
}
myArray::myArray(myArray&& emplace) : data(std::move(emplace.data)) {}
此外,我还有第二类,其中包含第一类元素的向量 (myArray)。
class Queue {
public:
Queue();
private:
std::vector<myArray> _queue;
};
Queue::Queue {
_queue.reserve(1000);
for(int a = 0; a < 10; a++)
for(int b = 0; b < 10; b++)
for(int c = 0; c < 10; c++)
_queue.emplace_back(a,b,c);
}
我的问题是:为什么在 Queue 构造函数的末尾调用 myArray 元素的析构函数? Queue 对象在我的主程序中仍然存在,但 myArray 的析构函数释放了分配的内存,因此我得到了分段错误。
有没有办法避免调用析构函数,或者直到队列对象生命周期结束时才调用它?
【问题讨论】:
-
myArray 对象被复制到向量中,存在双重删除问题。结帐规则三
-
@billz Queue 构造函数中没有 myArray 的复制。不过,队列可能被复制到其他地方。
标签: c++ vector constructor