I am wondering about this because of scope issues. For example, consider the code
typedef struct {
int x1;/*top*/
int x2;/*bottom*/
int id;
} sub
It returns a copy, which is what you want it to do. Changing it to return a reference will result in undefined behaviour in the assignment to line.
However, the idiomatic way to do this in C++ is with constructors and assignment lists. This encapsulates code and data structures better, and allows you to avoid the plethora of intermediate objects that compilers are free to construct/destruct/copy.
struct subline_t {
int x1;/*top*/
int x2;/*bottom*/
int id;
// constructor which initialises values with assignment list.
subline_t(int the_x1, int the_x2, int the_id) :
x1(the_x1),
x2(the_x2),
id(the_id)
{
}
};
int main(){
subline_t line2(0,0,0); // never requires a copy or assignment.
}
yes , the return is a copy
subline_t subline(int x1, int x2, int id) {
subline_t t = { x1, x2, id };
return t;
}
If you put a referencer, then its not a copy
subline_t & subline(int x1, int x2, int id) {
subline_t t = { x1, x2, id };
return t; // will result in corruption because returning a reference
}
Returing objects in C++ done by value and not by reference.
the reference to subline_t t goes out of scope
No, the object is copyed.
will the return statement always copy
Yes and not... Semantically it behaves like copy, but there is something that is called return value optimization that saves copy constructor.
foo make_foo()
{
foo f(1,2,3);
return f;
}
foo ff=make_foo(); /// ff created as if it was created with ff(1,2,3) -- RVO
foo ff2;
ff2=make_foo(); /// instance of foo created and then copied to ff2 and then old
/// instance destroyed
It will always return a copy.
If you want to avoid the performance hit of copying the object on return, you can declare a pointer, build an instance of the object using new, and return the pointer. In that case, the pointer will be copied, but the object won't be.
For the structure subline_t
you've defined, yes, it will always return a copy.
I do not agree and NOT RECOMMEND to return vector to change values: Is much faster pass as reference:
void vectorial(vector <double> a, vector <double> b, vector <double> &c)
{
c[0] = a[1] * b[2] - b[1] * a[2]; c[1] = -a[0] * b[2] + b[0] * a[2]; c[2] = a[0] * b[1] - b[0] * a[1];
}
//This is slow!!!:
vector <double> vectorial(vector <double> a, vector <double> b)
{
vector <double> c{ a[1] * b[2] - b[1] * a[2], -a[0] * b[2] + b[0] * a[2], a[0] * b[1] - b[0] * a[1] };
return c;
}
I tested on VS2015 with following results in release mode:
By reference:8.01 MOPs and returning vector: 5.09 MOPs 60% worse!
In debug mode things are much worse:
By reference:0.053 MOPS and return vector: 0.034 MOPs