gpt4 book ai didi

c++ - 我必须依赖编译器 NRVO 吗?

转载 作者:行者123 更新时间:2023-11-28 00:21:07 25 4
gpt4 key购买 nike

我需要调用一个函数为我返回一个对象。问题是对象有一个析构函数,它可以在函数输出被分配给另一个对象之前破坏数据。在我的程序中,我有一个 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,程序运行如下:

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
...

最佳答案

The problem is that the object has a destructor which can ruin the data before the function output is being assigned into another object.

这不是问题。对象要么被正确复制,要么通过优化消除不必要的复制。如果您的复制 ctor 正确实现,最终结果将是相同的(当然除了不太理想的代码)。如果对象复制非常昂贵,您可能应该使用写入语义上的复制,而实际的 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

如您所见,最终结果是相同的,只是效率较低(创建了临时对象)

关于c++ - 我必须依赖编译器 NRVO 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27411388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com