views:

264

answers:

5

Assume,

void proc(CString& str)
{
  str = "123";
}

void runningMethod()
{
  CString str="ABC";
  proc(str);
}

I understand that at the exit of runningMethod str will be deallocated automatically; in this case, how does C++ delete the old data ("ABC")?

Thanks,

Gil.

+5  A: 

"ABC" was overwritten when you said = "123".

Internally, a string is an array of characters. At start, it made a new buffer that contained {'A', 'B', 'C', '\0'}. When you assigned, it just wrote '1' over the 'A', and so on.

When it destructed, it deleted the buffer.

GMan
Would that 'overwrite' call the destructor of "ABC" string?
gilbertc
@gilbertc: What do you mean? The string has one internal buffer. It held "ABC", was modified to hold "123", then was deleted.
GMan
@gilbertc: Depends on how operator= is defined.What I'm not sure about is, is CString an alias of the char * type... If I knew that I'd be able to give a better answer.
Platinum Azure
It depends on the type CString. How is it implemented?
struppi
@struppi: CString is the string class included with Microsoft's MFC library.
Billy ONeal
@Billy: Ah well, thanks, as a UNIX person I did not know that.
struppi
A: 

The exact details depend on the implementation of CString, but the important bit is that you don't have to worry about allocation and deallocation now that the class takes care of it for you.

quamrana
+1  A: 

The same happens as if you'd write:

CString foo = "ABC";
foo = "123";
struppi
A: 

In most cases when you do your assignment in proc() "ABC" will be freed. This is usually done in overloaded operator method. For example here you have example how such overload looks like.

String& String::operator= (const String& other)
{
        char* otherdata = other.data;
        char* olddata = data;
        if (otherdata != 0)
        {
                data = new char[other.length+1];
                length = other.length;
                memcpy(data,otherdata,other.length+1);
        }
        else
        {
                data = 0;
                length = 0;
        }
        if (olddata != 0)
        {
                delete[] olddata;
        }
    return *this;
}
Michal Sznajder
No need to check for null before delete.
GMan
A: 
Noah Roberts