- #include <iostream>
- class A
- {
- public:
- A(const char* cname) : name(cname)
- {
- std::cout << "constructing " << cname << std::endl;
- }
- ~A(){
- std::cout << "destructing " << name.c_str() << std::endl;
- }
- A(A const& a)
- {
- if (name.empty()) name = "*tmp copy*";
- std::cout << "creating " << name.c_str() << " by copying " << a.name.c_str() << std::endl;
- }
- A& operator=(A const& a)
- {
- std::cout << "assignment ( " << name.c_str() << " = " << a.name.c_str() << " )"<< std::endl;
- return *this;
- }
- std::string name;
- };
- A foo()
- {
- A b("b");
- return b;
- }
- int main()
- {
- A a("a");
- a = foo();
- }
output without NRVO:
constructing a
constructing b
creating *tmp copy* by copying b
destructing b
assignment ( a = *tmp copy* )
destructing *tmp copy*
destructing a
output with NRVO:
constructing a
constructing b
assignment ( a = b )
destructing b
destructing a