The cheapest way to bind a local variable to closure

I believe the following method is the cheapest way to bind a local variable to a closure:

void ByRValueReference(A&& a) {
}

std::function<void ()> CreateClosureByRValueReference() {
  A a;
  std::function<void ()> f = std::bind(&ByRValueReference, std::move(a)); // !!!
  return f;
}

However, it does not compile under Clang 3.1:

error: no viable conversion from '__bind<void (*)(A &&), A>' to 'std::function<void ()>'

and gcc 4.6.1:

/usr/include/c++/4.6/functional:1778:2: error: no match for call to ‘(std::_Bind<void (*(A))(A&&)>) ()’

Am I breaking the standard or just broken standard libraries?

+5
source share
1 answer

This is by design std::bind. The full specification is specified in 20.8.9.1.2. The function template binds [func.bind.bind], but in this case the last marker of item 10 (which describes how the associated parameters are used) is applied:

- otherwise, the value tidand its type Viis equalTiD cv &

, std::move(a) , A ( ), , operator(), lvalue ( cv- cv- , ). rvalue.

:

std::bind([](A& a) { ByRValueReference(std::move(a)); }, std::move(a))

, , ( A ), std::bind .

+3

All Articles