Home > Backend Development > C++ > How Can I Achieve Move Capture in C 11 Lambdas?

How Can I Achieve Move Capture in C 11 Lambdas?

Barbara Streisand
Release: 2024-12-09 20:22:11
Original
847 people have browsed it

How Can I Achieve Move Capture in C  11 Lambdas?

Capturing by Move in a C 11 Lambda

Move Capture in C 14

C 14 introduces generalized lambda capture, which allows for move capture. This feature enables code like:

using namespace std;

auto u = make_unique<some_type>(some, parameters);  

go.run([u = move(u)] { do_something_with(u); }); 
Copy after login

Workaround for Move Capture in C 11

In C 11, move capture can be emulated using a helper function make_rref:

#include <cassert>
#include <memory>
#include <utility>

template <typename T>
struct rref_impl
{
    // ... (implementation omitted for brevity)
};

template<typename T> rref_impl<T> make_rref( T && x )
{
    return rref_impl<T>{ std::move(x) };
}
Copy after login

Example usage:

std::unique_ptr<int> p{new int(0)};
auto rref = make_rref(std::move(p));
auto lambda = [rref]() mutable -> std::unique_ptr<int> { return rref.move(); };
assert(lambda());
assert(!lambda());
Copy after login

Emulating Generalized Lambda Capture in C 11

Generalized lambda capture can also be emulated using a capture function:

#include <utility>

template <typename T, typename F>
class capture_impl
{
    // ... (implementation omitted for brevity)
};

template <typename T, typename F>
capture_impl<T,F> capture( T && x, F && f )
{
    // ... (implementation omitted for brevity)
}
Copy after login

Example usage:

std::unique_ptr<int> p{new int(0)};
auto lambda = capture(std::move(p), [](std::unique_ptr<int> &p) { return std::move(p); });
assert(lambda());
assert(!lambda());
Copy after login

The above is the detailed content of How Can I Achieve Move Capture in C 11 Lambdas?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template