c++ - Usefulness of move constructor -
this question has answer here:
- what move semantics? 11 answers
i found example on http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
#include <iostream> using namespace std; class arraywrapper { public: // default constructor produces moderately sized array arraywrapper () : _p_vals( new int[ 64 ] ) , _size( 64 ) {} arraywrapper (int n) : _p_vals( new int[ n ] ) , _size( n ) {} // move constructor arraywrapper (arraywrapper&& other) : _p_vals( other._p_vals ) , _size( other._size ) { cout<<"move constructor"<<endl; other._p_vals = null; } // copy constructor arraywrapper (const arraywrapper& other) : _p_vals( new int[ other._size ] ) , _size( other._size ) { cout<<"copy constructor"<<endl; ( int = 0; < _size; ++i ) { _p_vals[ ] = other._p_vals[ ]; } } ~arraywrapper () { delete [] _p_vals; } private: int *_p_vals; int _size; }; int main() { arraywrapper a(20); arraywrapper b(a); }
could give me examples (the useful situations) move constructor inside class takes action?
understood aim of kind of constructor, cannot identify when used in real application.
the move constructor not used in example, since a
lvalue. if had function returning arraywrapper
, i.e. arraywrapper func()
, result of function call rvalue, move constructor used when arraywrapper b(func())
.
this might start: http://thbecker.net/articles/rvalue_references/section_01.html
Comments
Post a Comment