Does return statement copy values

Solution 1:

Yes, in that case there will be a copy made. If you change the function declaration like this:

subline_t &subline(int x1, int x2, int id) {

then no copy will be made. However, in your specific case it would not be valid to return a reference to an object allocated on the stack. The problem is that the object would be destructed and invalidated before the caller had a chance to use it.

This is related to the common Return Value Optimization for C++ that can avoid doing an actual copy operation in the case you have described. The end result is (or should be) the same as if a copy were done, but you should be aware of the optimization. The presence of this optimization can, in some cases, change the observable behaviour of the program.

Solution 2:

In your case , it will return a copy

If your code was

subline_t& subline(int, int)

then it would return a reference, which would yield in undefined behaviour.

Solution 3:

Yes, for a function declared to return a struct, return of such a struct will copy it (though the compiler is empowered to optimize the copy away, essentially in cases where it can prove the optimization is semantically innocuous, you can reason "as if" the copying was guaranteed).

However, since you did tag this as C++, not C, why not supply your struct with a constructor, instead...? Seems clearer and more direct...!-)

Solution 4:

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
}