One day, I'm wondering whether there is memory copy when returning a string object. But, I find a weird thing. When I return an object in my function, I expect there is a copy construction to create a temporary object as the return value. So, I try the following code.
class Substring: public string
{
public:
Substring(const char* s)
:string(s)
{
}
~Substring()
{
cout << "Deconstruct" << endl;
}
};
Substring foo()
{
Substring ret("test");
printf("Inner address: %p\n", ret.c_str());
return ret;
}
int main()
{
Substring test = foo();
printf("Return address: %p\n", test.c_str());
return 0;
}
As I said, I'm expecting the Return address
is different from Inner address
. And Deconstruct
should be print out after Inner address
Here is what I got. It seems like ret
is deconstructed when the outside variable test
died, not the time when out of its scope! Why?
Inner address: 0x7ffed3a4cb40
Return address: 0x7ffed3a4cb40
Deconstruct