Hi, Forum.
How do you delete new memory allocated in a function call argument? Or should you?
So let's say you have a class with a constructor that has a pointer-to-object parameter (this example could apply to any function w/ a pointer parameter but for the sake of discussion, I'm using a constructor):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class tDailyViewPanel : public tScrolledWindow
{
public:
tDailyViewPanel(tDateTime* date);
... // rest of class interface
private:
tDateTime* m_date;
|
A user could instantiate this two ways as my novice brain sees it. They could create a new object dynamically with the "new" keyword such as this:
User Option #1
1 2 3
|
tScrolledWindow* selected = new tDailyViewPanel(new wxDateTime());
|
Or they may use a pointer to some already allocated tDateTime object, such as a member of a instantiating object.
User Option #2
1 2 3 4 5
|
m_selected = new tDailyViewPanel(m_member); // m_member is a tDateTime member of some instantiating/calling object and is deleted by the calling object's deconstructor.
}
|
At first, I would think the tDailyViewPanel constructor's implementation needs to initialize the m_date member with a shallow copy of the second argument.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
tDailyViewPanel::tDailyViewPanel(tDateTime* date) : tScrolledWindow()
{
... // doing stuff
m_date = date;
... // doing more stuff
}
|
I could then "delete" the memory allocated by the constructor call since "m_date" and "date" point to the same memory in User Option #1.
But if I do that and the user wants does User Option #2, I could delete memory that would be better deleted by the object/function that called the tDailyViewPanel constructor.
Alternatively, if i did a deep copy,
1 2 3 4 5 6 7 8 9 10 11 12 13
|
tDailyViewPanel::tDailyViewPanel(tDateTime* date) : tScrolledWindow()
{
... // doing stuff
m_date = new tDateTime(*date);
... // doing more stuff
}
|
wouldn't it create a memory leak in the case of User Option 1?
I must not understand the mechanics of this because it feels like I'm stuck between a memory leak or deleting memory I shouldn't. How do you manage memory allocated in a function call argument? Are smart pointers the only way?