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