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();
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
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.