[英]delete[] pointer being freed was not allocated
我正在使用new運算符創建一個動態分配的數組(之所以使用此數組,是因為我想節省使用向量的內存開銷)。 該錯誤發生在析構函數中,表示雖然顯然分配了釋放的指針,但未分配該指針。 構造函數和析構函數如下:
~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");
}
您必須應用“三個規則” :
C ++標准說:
非聯合類X的隱式定義的復制構造函數執行其子對象的成員復制。 [n3126.pdf第12.8§16節]
非聯合類X的隱式定義的副本分配運算符執行其子對象的成員式副本分配。 [n3126.pdf第12.8§30節]
因此, Path
類的隱式定義的復制構造函數和復制賦值運算符將不會為您調用new[]
。
定義執行所需分配的副本構造函數和副本分配執行者。
注意:
例如:
Path( const Path& other ); // non construction-copyable
Path& operator=( const Path& ); // non copyable
(或使用boost::noncopyable
)
std::vector<>
的典型開銷非常低,在真正重要的上下文中很少:請盡可能多地使用它以避免此類問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.