Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object by function call in C++

Tags:

c++

I would like to create an object, that I'm only going to use only once, by a function call.

The two approaches I've tried give the same result, but as I'm new to C++, I'm not sure if they're appropriate.

#include <iostream>
using namespace std;

struct Foo {
    Foo(const int x, const int y): x(x), y(y) {};
    Foo(Foo & myfoo): x(myfoo.x), y(myfoo.y) {
        cout << "copying" << endl;
    };
    const int x, y;
};

int sum(const Foo & myfoo) {
    return myfoo.x + myfoo.y;
}

Foo make_foo(const int x, const int y) {
    Foo myfoo (x, y);
    return myfoo;
}

int main () {
    // version 1
    cout << 1 + sum(Foo(2,3)) << endl;
    // version 2
    cout << 1 + sum(make_foo(2,3)) << endl;
}

Which of these approaches is "more correct"? What's the difference? I ran the code above with gcc and clang and both times I get

6
6

which means the copy constructor wasn't called either time.

Related: Calling constructors in c++ without new

Edit: Thanks, I already know RVO. I was just wondering if one method is preferred over the other


1 Answers

The two approaches are equivalent in this case.

What you are observing is Copy elision, or more specifically Return Value Optimization.

The compiler is smart enough to recognize that you don't need to construct the intermediate instance since you are just going to copy, then destroy it. Therefore, it just creates the final instance which is the target of the function return.

This optimization is explicitly allowed by the language standard, even though it means that your copy constructor gets bypassed. In other words, the functionality of a copy constructor getting called is not guaranteed.

like image 69
Brent Bradburn Avatar answered Jul 24 '26 23:07

Brent Bradburn