c++ - moving std::function into another std::function does not invoke move constructor on captured variables -
i have class a prints out message when constructed/copied/moved
class { public: a(std::string s) :s_(s) { std::cout << "a constructed\n"; } ~a() { std::cout << "a destructed\n"; } a(const a& a) :s_(a.s_) { std::cout << "a copy constructed\n"; } a(a&& a) :s_(std::move(a.s_)) { std::cout << "a moved\n"; } std::string s_; }; in main, construct instance of a, capture in lambda value, copy lambda std::function, , move std::function std::function
int main() { a("hello "); std::function<void()> f = [a]{ std::cout << a.s_; }; std::function<void()> g(std::move(f)); } this prints out following
a constructed copy constructed copy constructed destructed destructed destructed why move constructor of a not invoked? shouldn't last step of moving f g have invoked a's move constructor?
the copy constructor isn't called precisely because have moved std::function. because std::function can optionally store captured values on heap , retain pointer them. moving function requires moving internal pointer. msvc opts store captures on heap , gcc etc. opt store them on stack requiring captured values moved well.
edit: mooing duck pointing out in comment on question gcc storing captures on heap. actual difference seems gcc moves captures lambda std::function when constructed lambda.
Comments
Post a Comment