C++ destructor called before lifetime of scope

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.

kab*_*nus 5

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在这种情况下,对 所做的任何更改也会影响您的原始单词。

如果您的Words 包含动态分配的内存,则问题会更糟。假设您使用默认的复制构造函数,地址将被复制。因此,销毁本地Word将释放仍由原始 引用的内存Word,从而在下次访问时导致崩溃。

  • @PIprog3592 我对此表示怀疑。很可能,该词本身包含指针引用。因此,在复制时,您会创建一个浅表副本 - 因此,当本地字被销毁时,它会(可能)释放这些指针。原始数据不会被破坏,但仍会引用空闲内存(并崩溃)。如果没有完整的示例,我无法确定,但这似乎是有可能的。 (3认同)