#include <memory>
#include <functional>
class A{ //non-copyable
std::unique_ptr<int> a;
public:
void operator()(){} //non-const
};
void func(std::function<void(void)> f)
{}
int main()
{
A fobj;
func(fobj);
return 0;
}
如上,需要传递一个A的函数对象给func,并且fobj不能是const型的。怎样实现呢?
The following options are available:
Use the reference of A. Disadvantage: When A is destroyed, the reference becomes invalid.
Construct a shared_ptr using move semantics. Disadvantages: Additional runtime overhead, requires a movable construct.
Or through a wrapper that moves objects when copying (requires A movable construct):