C++ method parameter passed by reference - memory question
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 automat开发者_如何学JAVAically; in this case, how does C++ delete the old data ("ABC")?
Thanks,
Gil.
"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.
The same happens as if you'd write:
CString foo = "ABC";
foo = "123";
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.
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;
}
A couple things to keep in mind here. First, the operator= of a class will generally take care of deleting anything it used to refer to before assigning the new data. Well, that's not entirely true, often times a smart developer will implement operator= by first creating a copy of the incoming class and then swapping current data with the new temporary, which now has ownership and deletes it. The important part to remember though is that before the operator= function exists the old data has, generally speaking, been discarded.
The other thing to keep in mind is that "ABC" is a string literal. The standard doesn't really define how they have to be stored, it simply states limitations that allow certain usual implementations. Very often that string literal will appear as a read-only element within the program data. In that case it will never be deleted so long as the program's image is loaded into memory (when it's running basically). This is the whole reason why code like this is UB:
void f()
{
char * x = "hello"; // points to a string literal.
x[0] = 'H';
}
// correct implementation is:
void f()
{
char x[] = "hello"; // reserved an array of 6 characters and copies string literal content.
x[0] = 'H';
}
精彩评论