As we know, the string implementation of standard library must have allocated some stacks. We also know that the variable hello will be out of scope after the function end.
1. Is hello.~string called?
2. How do hello knows that it's out of stack?
Yes, at least twice (once for the temporary object, and again for the object actually stored in the vector).
When do we need to call destructor explicitly anyway?
Short answer: Never.
Long answer: Only when you are writing your own memory management system and using placement new to invoke the ctor (read: placement new isn't the same thing as the new operator).
Basically, don't worry about it. The whole point of the dtor is that it's called automatically. C++ takes care of it so you don't have to.
Does std::vector<SomeClass> remember to call destructor of elements that's removed from vector?
The reason I asked is I wanted to store pointers to a vector
std::vector<SomeClass *> Hello;
Latter I'll do
Hello.add (new SomeClass)
Obviously the delete operator won't be called if I do
Hello.clear latter.
So seems the work around is to simply create a class that contain the pointer rather than the pointer itself. And then specify new in the constructor and delete in the destructor.
Is that how the pro are doing it?
Let's just say SomeClass is a really big class. Also I want vector Hello to also contain possible derived class from SomeClass, which is impossible if I store the class straight rather than the pointer.
Is it save to say that you should call new only in constructor and delete only in destructor? I mean if we use standard library it's pretty rare that we should use pointer straight do we?
So seems the work around is to simply create a class that contain the pointer rather than the pointer itself. And then specify new in the constructor and delete in the destructor.
These are called smart pointers, and there are many already available if you don't feel like reinventing the wheel.
Specifically, boost has some you can use.
Also, boost has pointer containers that are designed for just this purpose.
Example:
1 2 3 4 5 6 7
boost::ptr_vector<SomeClass> Hello;
Hello.push_back( new SomeClass );
Hello.push_back( new SomeClass );
Hello.clear(); // this WILL delete both created classes
// no need for smart pointers