I’m a c++ beginner and now reading the C++ Primer. I have some problem about the destrucor:
-
in chapter 13.1.3: "In a destructor, there is nothing akin to the constructor initializer list to control how members are destroyed; the destruction part is implicit. What happens when a member is destroyed depends on the type of the member. Members of class type are destroyed by running the member’s own destructor. The built-in types do not have destructors, so nothing is done to destroy members of built-in type."
So if I have such a class:
class Foo {
~Foo() { delete pi; }
int *pi;
int i;
};
When an instance of Foo is going to be destroyed, according to the above text, the built in type variable int i will not be destroyed? Then how it will exist since the object to which it belongs has been destroyed.
-
In chapter 13.1.4: "The HasPtr class that we have used in the exercises is a good example (§ 13.1.1,p.499). That class allocates dynamic memory in its constructor. The synthesized destructor will not delete a data member that is a pointer. Therefore, this class needs to define a destructor to free the memory allocated by its constructor."
I understand that the synthesized destructor does not de-allocate the memory that has been allocated by
newand is pointed to by plain pointers, but here in the text, it indicates that the pointer object itself is also not deleted by the synthesized pointer. Still the example of classFoo, does that mean that after an object ofFooclass is destroyed, the pointer pi will not be destroyed ( so becomes an invalid pointer )?
>Solution :
What the spec means is that no code is run to clean up int i. It simply ceases to exist. Its memory is part of Foo and whenever a Foo instance is released then i goes with it.
For pointers the same is true, the pointer itself will simply disappear (its really just another number), but the pointer might point at something that needs to also be released. The compiler doesnt know if that is the case so you have to write a destructor.
This is why things like std::shared_ptr exist, they are clever pointers (aka ‘smart’) and the compiler does know if it points at something that needs to be released and will generate the correct code to do so. This is why you should always use smart pointers instead of ‘naked’ ones (like int *p)