Ste*_*ong 1 c++ stack memory-leaks memory-management heap-memory
I have a question about triggering a destructor for an object prematurely. I have an dynamically allocated array of pointers to dynamically allocated Word objects. The name of the array is words_. words_ is a class attribute of another class called Dictionary.
In my Dictionary class, I have a function where I access each Word object and call a member function of the Word class.
The below code triggers the destructor prematurely:
Word *curr_word_ptr = words_[idx]; // This line is okay, doesn't trigger destructor
Word curr_word = *curr_word_ptr; // This line triggers the destructor prematurely
curr_word.callMemberFunc();
Run Code Online (Sandbox Code Playgroud)
Because of the second line, as soon as the scope of the function ends, the destructor is called.
But if I access it through the array indices alone:
*(words_[idx]).callMemberFunc(); // The desctructor is not called prematurely
Run Code Online (Sandbox Code Playgroud)
Is the problem because I have a stack variable (not even a stack pointer variable) accessing a dynamically allocated object? Thus, when the scope of the function ends, both the stack variable (curr_word) and the dynamically allocated stack object gets destroyed?
Thank you.
Word curr_word = *curr_word_ptr;
defines a local Word
, that only lives in the local scope, your function. When the function exits, it is destroyed. Note it is a copy of the initial Word
that is destroyed, not the original.
如果您想要方便的语法以便不必全部取消引用或复制,请使用引用:
Word &word = *curr_word_ptr;
Run Code Online (Sandbox Code Playgroud)
这是 C++ 提供的语法糖,用于引用没有指针的对象(直接)。但请注意,word
在这种情况下,对 所做的任何更改也会影响您的原始单词。
如果您的Word
s 包含动态分配的内存,则问题会更糟。假设您使用默认的复制构造函数,地址将被复制。因此,销毁本地Word
将释放仍由原始 引用的内存Word
,从而在下次访问时导致崩溃。