Reputation: 1406
I need to call a function which returns back an object for me. The problem is that the object has a destructor which can ruin the data before the function output is being assigned into another object. In my program, I have an operator+ which adds two matrices and returns the sum of both matrices:
C=A+B
According to The Name Return Value Optimization (NRVO), the following code should not call the destructor right away:
Matrix operator+(const Matrix &m1, const Matrix &m2)
{
Matrix sum;
m1.clone(sum);
for...
for...
sum.members[i][j]+=m2.members[i][j];
return sum;
}
My problem is that I am not confident with trusting on NRVO as it depends the compiler. If I give the code to someone else, he might compile the code and his compiler gives a different result.
So, is there any way to force the compiler to give me what exactly I need or I must change my code to an undesirable form as following?
Matrix sum(Matrix &result, const Matrix &m1, const Matrix &m2)
edit:
Just to explain more, I assume by considering NRVO, the probram runs as following:
compiler reaches to C=A+B
operator + is called
object sum is created
object sum is calculated as sum of m1 and m2
sum is returned but its destructor is not called
the value of sum is directed to variable C
after function containing variable C reaches end, the destructor of C is called.
While when NRVO is not applied, I expect:
compiler reaches to C=A+B
operator + is called
object sum is created
object sum is calculated as sum of m1 and m2
sum is returned and its destructor is called which releases all data allocations
the return value of the operator+ is already destroyed so an invalid data is associated to variable C
...
Upvotes: 0
Views: 135
Reputation: 44258
The problem is that the object has a destructor which can ruin the data before the function output is being assigned into another object.
This is not a problem. Object either will be copied properly or unnecessary copy will be eliminated by optimization. If your copy ctor implemented properly the end result would be the same (except less optimal code of course). If object copy is prohibitively expensive you probably should use copy on write semantics and actual Matrix object would be a thin wrapper to real object created on the heap.
What will actually happen when NRVO is not applied:
compiler reaches to C=A+B
operator + is called
object sum is created
object sum is calculated as sum of m1 and m2
temporary object of type Matrix created as a copy of object sum
object sum destroyed
temporary assigned to C
as you can see end result is the same, just less effective (temporary object created)
Upvotes: 3