这就是我所拥有的:
class MyClass {
int holder;
public:
MyClass() {
holder = 5;
}
};
template<class T>
class First {
std::vector<T> items;
public:
First() {
T* tmp;
for (int i = 0; i < 20; i++) {
tmp = new T();
items.push_back(*tmp);
}
};
~First() {
for (int i = 0; i < 20; i++) {
delete items.at(i);
}
};
};
class Second {
std::vector<std::deque<First<MyClass>>> items;
public:
Second() {
std::deque<First<MyClass>>* tmp;
for (int i = 0; i < 10; i++) {
tmp = new std::deque<First<MyClass>>;
items.push_back(*tmp);
}
};
~Second() {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < items.at(i).size(); j++) {
delete items.at(i).at(j); // this deletes the "First" instances
}
delete items.at(i); // this deletes the deque
}
};
};
在我的main
中,我创建了Second
的实例并向其添加了First
个实例(通过未包含的方法)。在main
结尾处,我删除了Second
的实例,该实例应删除First
和deques
的所有实例。但是,我收到以下错误:
error: cannot delete expression of type 'value_type' (aka 'MyClass')
error: cannot delete expression of type 'value_type' (aka 'First<MyClass>')
error: cannot delete expression of type 'value_type' (aka 'std::deque<First<MyClass>>')
基本上,我的所有delete
命令都会抛出错误。我在这里错过了什么?我需要手动实现析构函数,因为我在堆上创建了一堆东西 - 对吗?
答案 0 :(得分:5)
您永远不会存储new
表达式的结果。您的代码应该如下所示:
First() {
T* tmp;
for (int i = 0; i < 20; i++) {
tmp = new T();
items.push_back(*tmp);
delete tmp; // result of "new" is still accessible here
}
}
~First() { }
或者像这样:
First() {
for (int i = 0; i < 20; i++) {
items.push_back(T());
}
}
或者就像这样:
First() : items(20) {}