Object behaviours

Lets say in the code below I create an instance of X called obj and then store something and then return it. Will this obj get destroyed after being passed?

1
2
3
4
5
X operator+(const X& rhs){
    //some operation
    return obj;
}
I'll assume you mean something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct X { 
    int val; 
};

X operator+(const X& lhs, const X& rhs) {
    X obj;
    obj.val = lhs.val + rhs.val;
    return obj;
}

int main() {
    X a, b;
    a.val = 5;
    b.val = 6;
    X sum = a+b;
    return 0;
}


In this case, sum will have val=11, as you would expect. As for whether obj is destroyed or not, that depends.

With no optimizations, obj is created at the start of operator+, and destroyed at the end, with its contents copied into sum. However, many compilers implement "Return Value Optimization" (RVO), which can allow this to be elided. In this case obj might never be destroyed, in the case where obj and sum become the same thing.

See http://coliru.stacked-crooked.com/a/b813712b661ec306
Last edited on
Topic archived. No new replies allowed.