Returning a CString will call the destructor?

250 Views Asked by At

What happenes if i return a CString from a method? will it call the destructor of the CString?

CString f(){

CString s = g();

return s;

}

const char* g(){ return new char[5]; }

Thanks :)

2

There are 2 best solutions below

3
cdhowie On BEST ANSWER

Not necessarily.

If your compiler implements Return Value Optimization (RVO) then it can set up the call to f() such that s is constructed where the caller would store the return value, and therefore it can elide the calls to the CString copy constructor and destructor. This optimization is one of the few exceptions permitted by the C++ standard to the as-if optimization rule.

If you are compiling with all optimizations disabled, you would likely see one or more calls to the CString copy constructor and destructor in processing the call to f().

0
Luis Colorado On

The compiler will call the destructor of any object that ceases to exist when you finish function execution. As s is declared local to the function f(), al local objects (as s is) will cease to exist and as such, the compiler will call their destructor.