memory management - C++: What happens to a dynamically allocated object created as an argument in a constructor call? -
say making new object of class foo, takes object of class bar constructor argument. if created object in manner:
foo myobj(new bar());
what happens in case new object? i've seen code similar example (with no name new object created argument). put delete
call free memory taken bar object?
it depends, if allocated in example, foo
class managing it, otherwise bar
leaked
class foo { public: foo(bar* bar) : m_bar{bar} {} ~foo() { delete m_bar; } private: bar* m_bar; };
or if have access c++11 have std::unique_ptr
class foo { public: foo(bar* bar) : m_bar{bar} {} private: std::unique_ptr<bar> m_bar; };
Comments
Post a Comment