c++11 - Copy constructor called for captured variable instead of move constructor -
when compiled gcc 4.7.2 or 4.8.1 , run following program
#include <stdio.h> #include <functional> class { public: a() { } a(const a& a) { printf("copy ctor\n"); } a(a&& a) { printf("move ctor\n"); } }; int main() { a; auto func = [a] { }; auto newfunc = std::move(func); return 0; } will give output:
copy ctor move ctor which seems normal.
however, when a a; changed const a;, output follows:
copy ctor copy ctor why move of lambda affected fact whether original variable has been const or not?
fwiw, msvc2012 makes 2 copies.
since not have const a&& move constructor not called. since move sets object it's default value cannot move const object.
keep in mind if move constructor overloaded correctly object moved. example try running version of code.
#include <stdio.h> #include <functional> class { public: a() { } a(const a& a) { printf("copy ctor\n"); } a(const a&& a) { printf("move ctor\n"); } }; int main() { const a; auto func = [a] { }; const auto newfunc = std::move(func); return 0; } run code , noticed object moved wether there const qualification or not.
Comments
Post a Comment