In C++, we can manage resources by objects, i.e. acquiring resource in Ctor, and releasing it in Dtor (RAII). This relies on C++'s automatic destructor invocation. But how is this done under the hood? For example, how C++ know to call Dtor for c1
but not c2
. (I know this must have been answered before, but all of my searches ended in topics explaining how to use RAII). Thanks!
class Cat;
Cat c1;
Cat* c2 = new Cat();
Edit:
I know I need to call delete for c2
. I just don't understand how Dtor is called when c1
goes out of scope.
c1
's destructor will be called (when it goes out of scope), not*c2
's. That's whynew
is seldom used in modern c++ (search for "c++ smart pointer" in your search engine of choice). – Invalidismstd::unique_ptr<Cat>
to have the destructor automatically called. – Insomuchscope
of a variable ends... – Guayaquilc2
too, just not theCat
destructor but theCat*
destructor, which is trivial. – Lumpendelete
your object. You should always calldelete
when you are finished with the object. – Richellec2
is disposed of. Not the pointed object. – Invalidismtemplate <typename T> struct Thing { T member; }
has an implicitly declared destructor, which is trivial ifT
's destructor is trivial ..." Rather than "... which is trivial ifT
's destructor is trivial, orT
is a pointer, or arithmetic, or array of trivially destructible, or ... type" – Junejuneau