[英]delete[] pointer being freed was not allocated
I am using the new operator to create a dynamically allocated array (I am using this one because I want to save on the memory overhead of using a vector). 我正在使用new运算符创建一个动态分配的数组(之所以使用此数组,是因为我想节省使用向量的内存开销)。 The error occurs in the destructor, saying the pointer being freed was not allocated although obviously it was. 该错误发生在析构函数中,表示虽然显然分配了释放的指针,但未分配该指针。 The constructors and destructors are as follows: 构造函数和析构函数如下:
~Path() {
printf("Path Destructor\n");
if(points) {
delete[] points;
}
}
Path(const std::vector<PathPoint>& points_) {
size = points_.size();
points = new PathPoint[size];
int i = 0;
for(const PathPoint& p : points_) {
points[i++] = p;
}
printf("Path created\n");
}
You have to apply The Rule of Three : 您必须应用“三个规则” :
The C++ standard says that : C ++标准说:
The implicitly-defined copy constructor for a non-union class X performs a memberwise copy of its subobjects. 非联合类X的隐式定义的复制构造函数执行其子对象的成员复制。 [n3126.pdf section 12.8 §16] [n3126.pdf第12.8§16节]
The implicitly-defined copy assignment operator for a non-union class X performs memberwise copy assignment of its subobjects. 非联合类X的隐式定义的副本分配运算符执行其子对象的成员式副本分配。 [n3126.pdf section 12.8 §30] [n3126.pdf第12.8§30节]
So the implicitly-defined copy constructor and copy assignment operator for your Path
class will not call new[]
for you. 因此, Path
类的隐式定义的复制构造函数和复制赋值运算符将不会为您调用new[]
。
Define a copy constructor and a copy assignment oerator that perform the required allocation. 定义执行所需分配的副本构造函数和副本分配执行者。
Note: 注意:
Eg : 例如:
Path( const Path& other ); // non construction-copyable
Path& operator=( const Path& ); // non copyable
(or use boost::noncopyable
) (或使用boost::noncopyable
)
std::vector<>
is very very low, there are few contexts where it really matters : use it as much as you can to avoid such problems. std::vector<>
的典型开销非常低,在真正重要的上下文中很少:请尽可能多地使用它以避免此类问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.