Reputation: 2860
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). 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");
}
Upvotes: 0
Views: 948
Reputation: 23813
You have to apply The Rule of Three :
The C++ standard says that :
The implicitly-defined copy constructor for a non-union class X performs a memberwise copy of its subobjects. [n3126.pdf section 12.8 §16]
The implicitly-defined copy assignment operator for a non-union class X performs memberwise copy assignment of its subobjects. [n3126.pdf section 12.8 §30]
So the implicitly-defined copy constructor and copy assignment operator for your Path
class will not call new[]
for you.
Define a copy constructor and a copy assignment oerator that perform the required allocation.
Note:
E.g. :
Path( const Path& other ); // non construction-copyable
Path& operator=( const Path& ); // non copyable
(or use 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.Upvotes: 3