Use std :: bind in lambda with std :: unique_ptr

// By const l-value reference
auto func2 = std::bind([](const std::unique_ptr< std::vector<int> >& pw) // fine
{
    std::cout << "size of vector2: " << pw->size() << std::endl;
}, std::make_unique<std::vector<int>>(22, 1));

//By non-const l-value reference
auto func3 = std::bind([](std::unique_ptr< std::vector<int> >& pw) // fine
{
    std::cout << "size of vector3: " << pw->size() << std::endl;
}, std::make_unique<std::vector<int>>(22, 1));

// By Value
auto func4 = std::bind([](std::unique_ptr< std::vector<int> > pw) // error
{
    std::cout << "size of vector4: " << pw->size() << std::endl;
}, std::make_unique<std::vector<int>>(22, 1));
func4(); // without this line, compilation is fine. The VS generates error for the calling of the bind object.
// By r-value reference
auto func5 = std::bind([](std::unique_ptr< std::vector<int> >&& pw) // error
{
    std::cout << "size of vector5: " << pw->size() << std::endl;
}, std::make_unique<std::vector<int>>(22, 1));
func5(); // without this line, compilation is fine.

Why don't func4 and func5 compile?

+4
source share
2 answers

func4causes an error because the lambda parameter is passed by value. But std::unique_ptrnot copied.

func5more complex, we can read from the std :: bind documentation :

g, , g(u1, u2, ... uM), , std::invoke(fd, std::forward<V1>(v1), std::forward<V2>(v2), ..., std::forward<VN>(vN)), fd std::decay_t<F> v1, v2,..., vN , .
...
arg lvalue: vN std:: invoke arg, vN T cv &, cv cv-, c g.

, std::make_unique<std::vector<int>>(22, 1) r-, l- , r.
, func3 .

+4

bind , .

( ). . std::invoke ++ 17.

. , , , bind , . - , , operator().

, . , , .


auto funcA =
  [pw=std::make_unique<std::vector<int>>(22,1)]
  {
    std::cout << "size of vector2: " << pw->size() << std::endl;
  };

auto funcB =
  [pw=std::make_unique<std::vector<int>>(22,1)]() mutable
  {
    std::cout << "size of vector2: " << pw->size() << std::endl;
  };

, , . .

funcA a const unique_ptr, funcB const unique_ptr. ptr; .

std::bind lambdas, ++, , . lambdas ++ 14, , bind - .

std::bind , , bind bind.

+2

Source: https://habr.com/ru/post/1671202/


All Articles