I tried the following on gcc 13.1 on C++ on C++11/17/20/23 but it fails to compile when the move or copy constructor is deleted.
If those constructors are not deleted, then named return value optimization works, and neither copy/move are done.
Interestingly enough, if I remove the name, and return the prvalue directly then the plain return value optimization works.
Can anyone provide an explanation for this?
#include <memory>
#include <iostream>
struct Foo{
Foo(int v): a{v} { std::cout << "Create!\n"; }
~Foo() { std::cout << "Destruct!\n"; }
Foo(const Foo&)=delete;
Foo(Foo&&)=delete;
int a;
};
// I DON'T WORK!
Foo makeFoo() {
Foo foo{5};
return foo;
}
// I WORK!
//Foo makeFoo() {
// return Foo{5};
//}
int main() {
auto foo = makeFoo();
std::cout << "Hello world! " << foo.a << "\n";
}