似乎它的簡單問題,但我懷疑。請運營商delete
銷燬全部Object
的元素當我撥打delete list
非空列表用運營商創建new
?當然會,但我需要確認。正如你所看到的Object
有構造函數,但沒有分配器。C++操作符新增並刪除內存泄漏與容器
代碼:
std::list<Object>* ptr_listObjects = new std::list<Object>();
OtherObject* ptr_null = NULL;
ptr_listObjects->push_back (Object(ptr_null, 'A'));
ptr_listObjects->push_back (Object(ptr_null, 'A'));
ptr_listObjects->push_back (Object(ptr_null, 'A'));
ptr_listObjects->push_back (Object(ptr_null, 'A'));
ptr_listObjects->push_back (Object(ptr_null, 'A'));
ptr_listObjects->push_back (Object(ptr_null, 'A'));
delete ptr_listObjects; // no any possible memory leaks? (Object does not use `new` operator)
class Object
{
public:
Object(OtherObject* ptr_other, char xxx):
ptr_OtherObject(ptr_other),
charflag(xxx)
{}
OtherObject* ptr_OtherObject;
char charflag;
};
我很確定它會。但處理這種情況的最簡單方法是創建一個析構函數,用於輸出消息並查看是否有輸出。 – StoryTeller
我假設你的意圖是*不*在本示例中練習類[Object]的[Rule of Three](http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming))。有時你不需要(對象不「擁有」ptr_OtherObject對象),但很難說這是否是其中的一種。希望你會知道(這是畢竟你的代碼)。 – WhozCraig
請檢查一下http://www.boost.org/doc/libs/1_52_0/libs/smart_ptr/smart_ptr.htm – czchlong