小编wat*_*dog的帖子

为什么不使用自动返回类型在此函数中使用clang删除副本?

我发现clang 8.x不会忽略gcc和msvc没问题的模板化类对象的副本的情况。在我的实际应用程序中,这种多余的副本非常昂贵,因此我试图深入了解它,并最终更好地了解了何时在C ++ 17中执行复制省略。

该问题显示在下面的代码片段中。以自动返回类型声明的,返回命名类对象的函数在其主体中具有一个额外的副本构造。如果将返回值重新编码为返回未命名的临时值,则会发生省略。如果对函数进行了编码以显式返回该类的实例(而不是auto),则会发生省略。

如果结构A没有模板参数,那么还将生成完全省略的代码。

该问题表明是否所有内容都不例外或允许内联(NOINLINE可以使您无需执行代码即可在Godbolt中查看问题)。

// compiled with -O2 -std=c++17
#if defined(_MSC_VER) && !defined(__clang__)
#define NOINLINE __declspec(noinline)
#else
#define NOINLINE __attribute__((noinline))
#endif

template<int P>
struct A {
  int data = 0;
  NOINLINE explicit A(int data_) noexcept : data(data_) { }
  NOINLINE ~A() noexcept { }
  NOINLINE A(const A& other) noexcept : data(other.data) { }
};


template <int P>
NOINLINE auto return_auto_A_nrvo(const A<P>& a) noexcept {
/* clang 6.0 thru 8.0 doesn't elide copy of 'result': 
   gcc and msvc …
Run Code Online (Sandbox Code Playgroud)

c++ clang c++11 c++17

5
推荐指数
1
解决办法
119
查看次数

标签 统计

c++ ×1

c++11 ×1

c++17 ×1

clang ×1