Re: ustring dtor



Hi Piscium,

On Wed, 22 Sep 2010 22:00:04 +0100 you wrote:
> I took a peek at the ustring source code. A ustring is stored like this:
> 
> std::string string_;
> 
OK, so that's a std::string instance as a member of the class. Its
memory is part of the ustring instance directly.

> And this is the the ustring dtor:
> 
> ustring::~ustring()
> {}
> 
> Note that it is an empty function.

Yes, because it doesn't do anything beyond the baseline default.
 
> I have a question, just for my own education, as I am a beginner in C++.
> 
> Why wasn't the dtor defined instead like below?
> 
> ustring::~ustring()
> {string_.clear()}

Because there's no reason to. When a class instance is destroyed, after
the destructor has run, any members of that instance are destroyed. For
members that are themselves class instances, this action includes
running the corresponding destructor. It is the responsibility of the
std::string class to clean up all its memory on destruction, and thus
destroying a ustring instance results in the std::string class
destructor cleaning up any memory owned by the string_ member.

Now, had the string_ member been defined as a pointer, then the ustring
destructor would have had to clean it up (by delete[]ing it) because
the member that is destroyed automatically would merely be a pointer.
Destroying a pointer has no effect on what it points to.

I think that's right; I don't have the definitive C++ standard to hand,
but see also http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.11

Cheers,
Rob


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]