![](/img/trans.png)
[英]Hash table - issue with destructor (pointer being freed was not allocated)
[英]Pointer being freed was not allocated - destructor
慢慢了解復制/移動構造函數、5 規則等。再加上對指針/引用的使用不太了解,我無法理解為什么我的析構函數會拋出下面的錯誤。 我知道它僅由析構函數和析構函數引起,並且在復制構造函數之后。
untitled(19615,0x104a60580) malloc: *** error for object 0x600000b74000: pointer being freed was not allocated
untitled(19615,0x104a60580) malloc: *** set a breakpoint in malloc_error_break to debug
代碼:
#include <string>
using namespace std;
typedef int size_type;
class user{
public:
user():
rank(1),
name("default"){
}
private:
int rank;
string name;
};
class account{
public:
account(size_type max_size):
owners(new user[max_size]),
max_size(max_size){
cout<<"normal constructor"<<endl;
}
account(account& other):
owners(other.owners),
max_size(sizeof(owners)){
cout<<"copy constructor called"<<endl;
}
account(account&& other):
owners(other.owners),
max_size(sizeof(owners)){
cout<<"move constructor called"<<endl;
}
~account(){
if(owners!= NULL) {
delete[] owners;
owners= 0;
}
cout<<"destructor called"<<endl;
}
private:
user* owners;
size_type max_size;
};
int main(){
account f(3);
account n(f);
}
我不明白為什么我的析構函數會拋出下面的錯誤。 我知道它是由析構函數和析構函數引起的
account f(3);
這個 object 的構造函數分配了一個數組。
account n(f);
您編寫的復制構造函數復制指向動態數組的指針。
n
首先被銷毀。 它的析構函數刪除了數組。 之后f
被銷毀。 它的析構函數也刪除了相同的數組並且程序的行為是未定義的,這導致了您觀察到的 output。
為防止分配被多次刪除,您必須強制執行 class 不變量(適用於所有成員函數的后置條件),即任何非空owners
值在 class 的所有實例中必須是唯一的。 要在復制構造函數(以及移動構造函數以及復制和移動賦值運算符)中保持該不變性,您不能像現在那樣復制指針。 我建議學習 RAII 成語。
更好的解決方案:不要使用擁有裸指針。 使用std::vector<user>
。
PS 復制構造函數應該接受對 const 的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.