我需要调用一个函数,它为我返回一个对象。问题是,对象有一个析构函数,它可以在将函数输出分配给另一个对象之前破坏数据。在我的程序中,我有一个operator+,它添加两个矩阵并返回两个矩阵的和:
C=A+B根据名称返回值优化(NRVO),以下代码不应该立即调用析构函数:
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;
}我的问题是,我对信任NRVO没有信心,因为它取决于编译器。如果我将代码交给其他人,他可能会编译代码,而他的编译器则会给出不同的结果。
那么,有没有办法迫使编译器给我确切的需要,或者我必须将我的代码修改成如下所示的不合适的形式?
Matrix sum(Matrix &result, const Matrix &m1, const Matrix &m2)编辑:
为了解释更多,我假设通过考虑NRVO,probram运行如下:
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.当NRVO未被应用时,我希望:
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
...发布于 2014-12-10 21:55:40
问题是,对象有一个析构函数,它可以在将函数输出分配给另一个对象之前破坏数据。
这不是问题。对象将被正确复制,或者通过优化消除不必要的复制。如果您的复制器实现得当,那么最终结果将是相同的(当然,最优代码除外)。如果对象复制非常昂贵,那么您可能应该在写语义上使用copy,而实际的Matrix将是堆上创建的真实对象的薄包装器。
如果不应用NRVO,实际会发生什么:
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正如您所看到的,最终结果是相同的,只是效率较低(创建的临时对象)。
https://stackoverflow.com/questions/27411388
复制相似问题