Is it possible to avoid the copy constructor when switching from the newly created object to a function?

advertisements

I'm trying to figure out is it possible to avoid calling the copy-constructor when passing a just-created object to a function? I don't want to use this object any more, I'd just like to name the temporary and pass it by value to some other function.

I know that in C++11 I can just move this object, but I'm concerned how to improve this in C++03. So essentially, I'm interested in eliminating the copy-constructor call in the code below:

Snippet:

#include <iostream>

struct Foo
{
    Foo(void) { std::cout << "Default ctr\n"; };
    Foo(const Foo& f) { std::cout << "Copy ctr\n"; }
};

void bar(Foo f)
{
    std::cout << "Inside bar\n";
}

int main()
{
    Foo f;
    bar(f);
    bar(Foo());
}

Possible result:

Default ctr
Copy ctr
Inside bar
Default ctr
Inside bar

Compilation string:

g++ -O3 -Wall -pedantic main.cpp && ./a.out

I.e. to use some kind of copy-elision but on an argument passed to a function, not on a return value (NRVO).


Pass by value implies copying. This copying can be elided but semantically pass by value is still copying. You can pass by reference as well to avoid this copy. Note that these are the only situations in which copy elision are permitted:

  • in a return statement
  • in a throw-expression
  • with a temporary that hasn't been bound to a reference
  • and another to do with exceptions

That's why in:

bar(f);
bar(Foo());

only the second involves copy elision. Pre-C++11, just use a reference or use Boost.