gpt4 book ai didi

c++ - GCC NRVO/RVO 警告

转载 作者:IT老高 更新时间:2023-10-28 21:58:32 27 4
gpt4 key购买 nike

是否有任何警告,让我们知道 NRVO/RVOGCC 中是否执行?

我发现-fno-elide-constructors关闭NRVO/RVO,但是NRVO/RVO有它自己的条件发生并且有时不会发生。有必要知道 NRVO/RVO 是否发生,以便了解何时发生额外的复制构造。

我对编译时特性特别感兴趣。如果有一些特定的 #pragma GCC... (它会在其自身之后立即激活诊断)或使用静态断言机制的东西,那就太好了。

最佳答案

我不知道任何 gcc 特定的诊断消息或其他可以轻松解决您的任务的方法。正如您所发现的,-fno-elide-constructors 将禁用复制/移动省略,因此您将确定至少在这种情况下不会发生 (N)RVO。

但是,快速浏览this C++11 working draft 的第 12.8 节中的第 31 段声明:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization. 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

...

  • when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

...

当发生复制/移动省略时,本地自动对象与临时(返回)对象相同,而临时(返回)对象又与“存储”对象(存储返回值的位置)相同。因此本地自动对象与存储对象相同,这意味着指针比较将等于 true。一个简单的例子来证明这一点:

#include <iostream>
#include <vector>

std::vector<int> testNRVO(int value, size_t size, const std::vector<int> **localVec)
{
std::vector<int> vec(size, value);

*localVec = &vec;

/* Do something here.. */

return vec;
}

int main()
{
const std::vector<int> *localVec = nullptr;

std::vector<int> vec = testNRVO(0, 10, &localVec);

if (&vec == localVec)
std::cout << "NRVO was applied" << std::endl;
else
std::cout << "NRVO was not applied" << std::endl;
}

启用/禁用 -fno-elide-constructors 按预期更改打印的消息。注意:在最严格的意义上,指针比较可能取决于未发生 (N)RVO 时的未定义行为,因为本地自动对象不存在。

进行指针比较会增加麻烦,但具有编译器独立性的优势。

关于c++ - GCC NRVO/RVO 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20674231/

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