gpt4 book ai didi

c++ - 为什么这里不应用 NRVO?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:35:30 25 4
gpt4 key购买 nike

当我在 VS2010 中运行此代码时,不应用 NRVO。

#include <stdio.h>

class A
{
public:

A() { printf( "I am in constructor\n" ); }
A(const A& a) { printf( "I am in copy constructor\n" ); }
~A() { printf( "I am in destructor\n" ); }
int i;
};

A f(int j)
{
A a;
if ( j ) return a;
a.i = j;
return a;
}

int main()
{
A a;
a = f(5);
}

编辑:这与析构函数有关。当我注释掉它的行时,使用了 NRVO。但这是为什么呢?

最佳答案

Why NRVO is not applied here?

如果这纯粹是您的好奇心,并且您想知道 VC10 如何通过算法决定是否执行 NRVO,那么唯一能够可靠地回答这个问题的人就是那些了解 VC10 内部工作原理的人 - 那些编写它的人.

据我所知,根据 C++11 标准,编译器被允许在这种情况下执行 NRVO,不这样做只是编译器的决定——不是因为任何有效性约束。根据第 12.8/31 段:

[...] This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

[...]

但是,如果您希望能够强制您的编译器执行 NRVO,那么答案是“您不能”。

是否应用 NRVO 完全由编译器决定。你不能指望它,你也不能指望它被执行。据我所知,这是所谓的“as-if”规则的唯一异常(exception)。

也就是说,随着您提高优化级别,执行 NRVO 的机会也会增加。

关于c++ - 为什么这里不应用 NRVO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16038511/

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