I think answers to this question Why isn't the copy constructor elided here? are really useful in answering your question. Copy elision is not used in your example
Foo getBigData()
{
Bar b;
b.workOnBigData();
return b.bigData;
}
since this requiment is not fullfiled (http://en.cppreference.com/w/cpp/language/copy_elision):
the return statement's expression is the name of a non-volatile object
with automatic storage duration ...
and which has the same type (ignoring top-level cv-qualification) as
the return type of the function, then copy/move is omitted
In your example Bar is a variable with automatic storage duration but your return Foo. If you change your Bar class a compiler will start using copy elision:
#include <iostream>
#include <typeinfo>
using namespace std;
struct Foo
{
Foo() { cout << "Foo()\n"; }
~Foo() { cout << "~Foo()\n"; }
Foo(const Foo&) { cout << "Foo(Foo&)\n"; }
Foo(Foo&&) { cout << "Foo(Foo&&)\n"; }
int d;
};
struct Bar
{
Foo bigData;
void workOnBigData() { /*...*/ }
};
struct Bar2
{
void workOnBigData(Foo&) { /*...*/ }
};
Foo getBigData()
{
Bar b;
b.workOnBigData();
return b.bigData;
}
Foo getBigData2()
{
Foo f;
Bar2 b;
b.workOnBigData(f);
return f;
}
int main()
{
{
Foo f = getBigData();
}
cout << "---" << endl;
{
Foo f = getBigData2();
}
}
#include <iostream>
#include <typeinfo>
using namespace std;
struct Foo
{
Foo() { cout << "Foo()\n"; }
~Foo() { cout << "~Foo()\n"; }
Foo(const Foo&) { cout << "Foo(Foo&)\n"; }
Foo(Foo&&) { cout << "Foo(Foo&&)\n"; }
int d;
};
struct Bar
{
Foo bigData;
void workOnBigData() { /*...*/ }
};
struct Bar2
{
void workOnBigData(Foo&) { /*...*/ }
};
Foo getBigData()
{
Bar b;
b.workOnBigData();
return b.bigData;
}
Foo getBigData2()
{
Foo f;
Bar2 b;
b.workOnBigData(f);
return f;
}
int main()
{
{
Foo f = getBigData();
}
cout << "---" << endl;
{
Foo f = getBigData2();
}
}
This is what it outputs:
$ ./a.out
Foo()
Foo(Foo&)
~Foo()
~Foo()
---
Foo()
~Foo()