如何允许 C++ 类的复制省略构造(不仅仅是 POD C 结构)

2022-01-11 00:00:00 optimization macros c++ c++11

考虑以下代码:

#include <iostream>
#include <type_traits>

struct A
{
  A() {}
  A(const A&) { std::cout << "Copy" << std::endl; }
  A(A&&) { std::cout << "Move" << std::endl; }
};

template <class T>
struct B
{
  T x;
};

#define MAKE_B(x) B<decltype(x)>{ x }

template <class T>
B<T> make_b(T&& x)
{
  return B<T> { std::forward<T>(x) };
}

int main()
{
  std::cout << "Macro make b" << std::endl;
  auto b1 = MAKE_B( A() );
  std::cout << "Non-macro make b" << std::endl;
  auto b2 = make_b( A() );
}

这会输出以下内容:

宏制作b
非宏制作b
移动

Macro make b
Non-macro make b
Move

请注意,b1 的构建不需要移动,但 b2 的构建需要移动.

Note that b1 is constructed without a move, but the construction of b2 requires a move.

我还需要类型推导,因为A在现实生活中可能是一个复杂的类型,很难显式编写.我还需要能够嵌套调用(即 make_c(make_b(A()))).

I also need to type deduction, as A in real life usage may be a complex type which is difficult to write explicitly. I also need to be able to nest calls (i.e. make_c(make_b(A()))).

这样的功能可能吗?

进一步的想法:

N3290 Final C++0x 草稿第 284 页:

这种复制/移动操作的省略,称为复制省略,在以下情况:

This elision of copy/move operations, called copy elision, is permitted in the following circumstances:

当一个临时类对象有未绑定到参考 (12.2)将被复制/移动到一个类具有相同 cv 不合格的对象类型,复制/移动操作可以是通过构造临时省略对象直接进入目标省略复制/移动

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

不幸的是,我们似乎无法将函数参数的副本(和移动)省略到函数结果(包括构造函数),因为这些临时对象要么绑定到引用(当通过引用传递时),要么不再是临时对象(当通过引用传递时)价值).在创建复合对象时,似乎删除所有副本的唯一方法是将其创建为聚合.但是,聚合有一定的限制,例如要求所有成员都是公共的,并且没有用户定义的构造函数.

Unfortunately this seems that we can't elide copies (and moves) of function parameters to function results (including constructors) as those temporaries are either bound to a reference (when passed by reference) or no longer temporaries (when passed by value). It seems the only way to elide all copies when creating a composite object is to create it as an aggregate. However, aggregates have certain restrictions, such as requiring all members be public, and no user defined constructors.

我认为 C++ 允许对 POD C 结构聚合构造进行优化但不允许对非 POD C++ 类构造进行相同的优化是没有意义的.

I don't think it makes sense for C++ to allow optimizations for POD C-structs aggregate construction but not allow the same optimizations for non-POD C++ class construction.

有没有办法允许非聚合构造的复制/移动省略?

Is there any way to allow copy/move elision for non-aggregate construction?

我的回答:

此构造允许省略非 POD 类型的副本.我从 大卫罗德里格斯的回答如下.它需要 C++11 lambda.在下面的这个例子中,我改变了 make_b 来接受两个参数,以使事情变得不那么琐碎.没有调用任何移动或复制构造函数.

This construct allows for copies to be elided for non-POD types. I got this idea from David Rodríguez's answer below. It requires C++11 lambdas. In this example below I've changed make_b to take two arguments to make things less trivial. There are no calls to any move or copy constructors.

#include <iostream>
#include <type_traits>

struct A
{
  A() {}
  A(const A&) { std::cout << "Copy" << std::endl; }
  A(A&&) { std::cout << "Move" << std::endl; }
};

template <class T>
class B
{
public:
  template <class LAMBDA1, class LAMBDA2>
  B(const LAMBDA1& f1, const LAMBDA2& f2) : x1(f1()), x2(f2()) 
  { 
    std::cout 
    << "I'm a non-trivial, therefore not a POD.
" 
    << "I also have private data members, so definitely not a POD!
";
  }
private:
  T x1;
  T x2;
};

#define DELAY(x) [&]{ return x; }

#define MAKE_B(x1, x2) make_b(DELAY(x1), DELAY(x2))

template <class LAMBDA1, class LAMBDA2>
auto make_b(const LAMBDA1& f1, const LAMBDA2& f2) -> B<decltype(f1())>
{
  return B<decltype(f1())>( f1, f2 );
}

int main()
{
  auto b1 = MAKE_B( A(), A() );
}

如果有人知道如何更巧妙地实现这一点,我会非常有兴趣看到它.

If anyone knows how to achieve this more neatly I'd be quite interested to see it.

之前的讨论:

这在某种程度上源于对以下问题的回答:

This somewhat follows on from the answers to the following questions:

能否优化从临时对象创建复合对象离开?
使用表达式模板避免#define
在构建复合对象时消除不必要的副本

推荐答案

正如 Anthony 已经提到的,标准禁止从函数的参数到相同函数的返回的复制省略.做出该决定的基本原理是复制省略(和移动省略)是一种优化,程序中的两个对象通过该优化合并到相同的内存位置,也就是说,通过使两个对象为一个来省略复制.下面是(部分)标准引用,后面是允许复制省略的一组情况,不包括该特定情况.

As Anthony has already mentioned, the standard forbids copy elision from the argument of a function to the return of the same function. The rationale that drives that decision is that copy elision (and move elision) is an optimization by which two objects in the program are merged into the same memory location, that is, the copy is elided by having both objects be one. The (partial) standard quote is below, followed by a set of circumstances under which copy elision is allowed, which do not include that particular case.

那么是什么让这种特殊情况有所不同?区别基本上在于原始对象和复制对象之间存在函数调用这一事实,而函数调用意味着需要考虑额外的约束,特别是调用约定.

So what makes that particular case different? The difference is basically that the fact that there is a function call between the original and the copied objects, and the function call implies that there are extra constraints to consider, in particular the calling convention.

给定一个函数T foo(T),以及一个用户调用T x = foo(T(param));,在一般情况下,单独编译,编译器将在调用约定要求第一个参数所在的位置创建一个对象 $tmp1.然后它将调用该函数并从 return 语句初始化 x.这是复制省略的第一个机会:通过小心地将 x 放置在返回的临时位置 x 和从 foo 返回的对象成为单个对象,并且该副本被省略.到现在为止还挺好.问题是调用约定通常不会将返回的对象和参数放在同一位置,因此 $tmp1x 不能是单个内存中的位置.

Given a function T foo( T ), and a user calling T x = foo( T(param) );, in the general case, with separate compilation, the compiler will create an object $tmp1 in the location that the calling convention requires the first argument to be. It will then call the function and initialize x from the return statement. Here is the first opportunity for copy elision: by carefully placing x on the location where the returned temporary is, x and the returned object from foo become a single object, and that copy is elided. So far so good. The problem is that the calling convention in general will not have the returned object and the parameter in the same location, and because of that, $tmp1 and x cannot be a single location in memory.

如果没有看到函数定义,编译器不可能知道函数参数的唯一目的是用作返回语句,因此它不能省略那个额外的副本.可以说,如果函数是 inline 则编译器将缺少额外的信息来理解用于调用函数的临时值、返回值和 x 是单个对象.问题是,如果代码实际上是内联的(不仅标记为 inline,而且 实际上是内联),如果需要函数调用,则只能省略该特定副本,则无法省略副本.如果标准允许在内联代码时省略该副本,则意味着程序的行为会因编译器而不是用户代码而有所不同――inline 关键字不会强制内联, 仅表示同一函数的多个定义并不代表违反 ODR.

Without seeing the function definition the compiler cannot possibly know that the only purpose of the argument to the function is to serve as return statement, and as such it cannot elide that extra copy. It can be argued that if the function is inline then the compiler would have the missing extra information to understand that the temporary used to call the function, the returned value and x are a single object. The problem is that that particular copy can only be elided if the code is actually inlined (not only if it is marked as inline but actually inlined) If a function call is required, then the copy cannot be elided. If the standard allowed that copy to be elided when the code is inlined, it would imply that the behavior of a program would differ due to the compiler and not user code --the inline keyword does not force inlining, it only means that multiple definitions of the same function do not represent a violation of the ODR.

请注意,如果变量是在函数内部创建(与传递给它相比),如:T foo() { T tmp;...;返回 tmp;} T x = foo(); 然后可以省略两个副本:对于必须创建 tmp 的位置没有限制(它不是函数的输入或输出参数因此编译器能够将它重新定位到任何地方,包括返回类型的位置,并且在调用端,x 可以像前面的示例一样小心地定位在同一个返回语句的位置,这基本上意味着 tmp、return 语句和 x 可以是一个对象.

Note that if the variable was created inside the function (as compared to passed into it) as in: T foo() { T tmp; ...; return tmp; } T x = foo(); then both copies can be elided: There is no restriction as of where tmp has to be created (it is not an input or output parameter to the function so the compiler is able to relocate it anywhere, including the location of the returned type, and on the calling side, x can as in the previous example be carefully located in the location of that same return statement, which basically means that tmp, the return statement and x can be a single object.

对于您的特定问题,如果您求助于宏,则代码是内联的,对对象没有限制,并且可以省略副本.但是如果你添加一个函数,你就不能从参数中删除副本到 return 语句.所以只是避免它.不要使用将移动对象的模板,而是创建一个将构造对象的模板:

As of your particular problem, if you resort to a macro, the code is inlined, there are no restrictions on the objects and the copy can be elided. But if you add a function, you cannot elide the copy from the argument to the return statement. So just avoid it. Instead of using a template that will move the object, create a template that will construct an object:

template <typename T, typename... Args>
T create( Args... x ) {
   return T( x... );
}

并且该副本可以被编译器删除.

And that copy can be elided by the compiler.

请注意,我没有处理移动构建,因为您似乎关心移动构建的成本,即使我认为您在错误的树上吠叫.鉴于一个鼓舞人心的真实用例,我很确定这里的人们会想出几个有效的想法.

Note that I have not dealt with move construction, as you seem concerned on the cost of even move construction, even though I believe that you are barking at the wrong tree. Given a motivating real use case, I am quite sure that people here will come up with a couple of efficient ideas.

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.

相关文章