variable assignment - output from move constructor class -
class test { char *str; public: test(char *p_str) /**default constructor**/ { cout<<"default\n"; int l = strlen(p_str) + 1; str = (l ? new char[l] : 0); memcpy(str,p_str,l); } test(const test& ob) /**copy**/ { cout<<"copy\n"; int l = strlen(ob.str) + 1; str = (l ? new char[l] : 0); memcpy(str,ob.str,l); } test(test&& ob) /**move constructor **/ { cout<<"move constructor\n"; str = ob.str; ob.str = nullptr; } void my_swap(test &ob1 , test &ob2) /**swap function**/ { swap(ob1.str , ob2.str); } test& operator=(test ob) /**copy called because of pass value **/ { cout<<"copy assignment operator\n"; my_swap(*this,ob); return *this; /**copy destroyed object passed value destroyed after function returns;**/ } ~test() { cout<<"destructor\n"; delete[] str; } void print_str() { cout<<str<<"\n"; } };
the above class contains simple implementation of rule of 5 in c++.now when vector of class created following.
int main() { vector<test> vec1; vec1.push_back(test("hi!there")); return 0; }
i following output
default
move constructor
destructor
destructor
and when 1 more object pushed vector this
int main() { vector<test> vec1; vec1.push_back(test("hi!there")); vec1.push_back(test("hello! there")); return 0; }
the output
default
move constructor
destructor
default
move constructor
copy
destructor
destructor
destructor
destructor
now question why copy constructor called in second case , not first.
thanku
since have 5 destructor calls instead of 4 assume vector had reallocate it's internal storage when tried push second item. means vector had move first pushed item newly allocated (larger) memory area. when vector reallocates storage , has transfer items old memory block the new one, may happen item transferred copy instead of move. reason: how enforce move semantics when vector grows?
in case correct solution using vec1.reserve(2)
(before pushing items) avoid unnecessary reallocation if reallocation happens move. frequent reallocation target of memory usage optimization.
Comments
Post a Comment