c++ - GCC NRVO/RVO 警告

标签 c++ gcc g++ copy-elision

是否有任何警告,让我们知道 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/

相关文章:

c++ - 一旦被捕获,如何从 std::exception 中获取原始异常?

linux - "arm-linux-gcc"和 "sim-panalyzer"导致的奇怪错误位于glibc函数 "dl_aux_init"

c++ - 可识别 C++ 的 Diff 实用程序

c++ - 为什么没有为函数参数省略拷贝

c++ - 是否可以在仅禁用某些功能的严格别名的同时启用链接时优化?

c++ - OpenCL 缓冲区数组 - clEnqueueWriteBuffer -36

c++ - 使用数组 C++ 进行组合

c++ - 在类模板中定义变量模板

c++ - 使用 minGW 构建 Boost

c++ - 在 Debian 8.7 上安装 g++ 7.0.1