Hello, consider this complete program:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
class Hanna
{
public:
Hanna(const string& s)
:
s_(s)
{ cout << "normal ctor, name = " << s_ << endl; }
Hanna(const Hanna& inst)
:
s_(inst.s_)
{ cout << "copyctor, name = " << s_ << endl; }
~Hanna() { cout << "cleaning up " << s_ << endl; }
Hanna& operator=(const Hanna& rhs)
{
s_ = rhs.s_;
cout << "in operator=(), name = " << s_ << endl;
return *this;
}
private:
string s_;
};
static Hanna
func(const string& s)
{
Hanna anobj(s);
return anobj;
}
int
main()
{
cout << "Testing catching return value in normal object." << endl;
{
Hanna a = func("not catching const ref");
(void)a;
}
cout << "\nTesting catching return value in a const reference" <<
endl;
{
const Hanna& b = func("catching const ref");
(void)b;
}
return 0;
}
When run, the outut is:
$ ./runme
Testing catching return value in normal object.
normal ctor, name = not catching const ref
cleaning up not catching const ref
Testing catching return value in a const reference
normal ctor, name = catching const ref
cleaning up catching const ref
The program has been compiled with optimizations disabled (and
debugging turned on). I thought that I had to catch the return value in
a const reference (if possible), if I wanted to avoid ctor/dtor calls
but seems I dont have to...is this optimization part of the C++
specification?
/ E