开发者

Nicer way to avoid moves/copies in C++0x

开发者 https://www.devze.com 2023-03-20 12:01 出处:网络
This question follows on from How to pass by lambda in C++0x?, but perhaps this is a clearer way to ask the question.

This question follows on from How to pass by lambda in C++0x?, but perhaps this is a clearer way to ask the question.

Consider the following code:

#include <iostream>

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

class A
{
public:
  A() : i(42) {};
  A(const A& a) : i(a.i) { std::cout << "Copy " << std::endl; }
  A(A&& a) : i(a.i) { std::cout << "Move " << std::endl; }
  int i;
};

template <class T>
class B
{
public:
  B(const T& x_) : x(x_) {}
  B(T&& x_) : x(std::move(x_)) {}
  template <class LAMBDA_T>
  B(LAMBDA_T&& f, decltype(f())* dummy = 0) : x(f()) {}
  T x;
};

template <class T>
auto make_b_normal(T&& x) -> B<typename std::remove_const<typename std::remove_reference<T>::type>::type>
{
  return B<typename std::remove_const<typename std::remove_reference<T>::type>::type>(std::forward<T>(x));
}

template <class LAMBDA_T>
auto make_b_macro_f(LAMBDA_T&& f) -> B<decltype(f())>
{
  开发者_StackOverflow社区return B<decltype(f())>( std::forward<LAMBDA_T>(f) );
}

#define MAKE_B_MACRO(x) make_b_macro_f(LAMBDA(x))

int main()
{
  std::cout << "Using standard function call" << std::endl;
  auto y1 = make_b_normal(make_b_normal(make_b_normal(make_b_normal(A()))));
  std::cout << "Using macro" << std::endl;
  auto y2 = MAKE_B_MACRO(MAKE_B_MACRO(MAKE_B_MACRO(MAKE_B_MACRO(A()))));
  std::cout << "End" << std::endl;
}

Which outputs the following:

Using standard function call
Move 
Copy 
Copy 
Copy 
Using macro
End

It is clear that the macro version somehow elides all move/copy constructor calls, but the function version does not.

I assume that there is a syntactically nice way of eliding all the moves and copies without lots of macros in C++0x, but I can't figure it out.

Reason:

I plan to use such code without moves or copies for building parameter packs, i.e.

auto y = (_blah = "hello", _blah2 = 4);
f(y, (_blah3 = "world", _blah4 = 67));

And have these not have no extra moves/copies compared to non parameter code.


You failed to provide a move constructor for B. When that is provided, then on Visual Studio 2010 I get a bunch of moves. The reason that it doesn't ellide any of the moves is because you created a B<B<B<B<A>>>>.

Compilers are still very immature w.r.t. move ellision. I would expect them to get better at it later.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号