Skip to content

Instantly share code, notes, and snippets.

@coryan
Created December 30, 2018 20:33
Show Gist options
  • Save coryan/19f7d4199f32c82249b43c6f9ae52486 to your computer and use it in GitHub Desktop.
Save coryan/19f7d4199f32c82249b43c6f9ae52486 to your computer and use it in GitHub Desktop.
// Also available here:
// https://godbolt.org/z/CAmvFF
#include <functional>
#include <memory>
struct MyFunctor {
MyFunctor() : x(0) {}
MyFunctor(MyFunctor const& rhs) : x(1) {}
MyFunctor(MyFunctor&& rhs) : x(2) {}
int operator()() const { return x; }
int x;
};
int F(MyFunctor&& f) {
auto tmp = [f]() {
return f();
};
return tmp();
}
int G(MyFunctor&& f) {
auto tmp = [t = std::move(f)]() {
return t();
};
return tmp();
}
int f = F(MyFunctor()); // f==1 implies copy ctor was called.
int g = G(MyFunctor()); // g==2 implies move ctor was called.
#if WITH_MAIN
#include <iostream>
std::function<int()> R(MyFunctor&& f) {
auto tmp = [&f]() {
return f();
};
return tmp;
}
int main() {
auto fun = R(MyFunctor());
std::cout << "fun()=" << fun() << std::endl;
std::cout << "f = " << f << std::endl;
std::cout << "g = " << g << std::endl;
return 0;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment