c++11 - C++ Embded lambda in initializer list for const vector member -
i have class has const vector
member holds unique pointers objects. when constructed, sequence
object should steal ownership of vector of unique pointers passed constructor sequence object owner of objects owned unique pointers in vector parameter.
class sequence { const std::vector< std::unique_ptr< statement > > m_statements; sequence( std::vector< std::unique_ptr< statement > > & statements ); };
the first time tried implement constructor, did following :
sequence::sequence( vector< unique_ptr< statement > > & statements ) m_statements( statements ) { }
but of course not compile since 1 can't copy-construct unique_ptr
, can't copy-construct vector
.
c++ doesn't allow initialize const members in body of constructor (like java final members), within initializer list. thus, 1 possible solution drop const
modifier of m_statement
and, using loop, move content 1 vector other in body of constructor.
but want keep const
modifier.
so came solution seems compile, because i'm new c++11, i'm not exacly. idea embed loop described above lambda function initialize m_statement
within initializer list using loop , still keep const
modifier on m_statement
.
sequence::sequence( vector< unique_ptr< const statement > > & statements ) : m_statements(([ & statements ] { vector< unique_ptr< const statement > > copied_vec; for( auto & stm : statements ) copied_vec.push_back( move( stm ) ); return copied_vec; })()) { }
this compiles. i'm not sure happens starting @ return statement of lambda function.
i assume copy of copied_vec made , returned. happens when return value vector of unique pointers ? correct way want, despite being weird, or must drop const
modifier on m_statetent
? thank you.
am missing reason why move constructor can't used?
sequence::sequence( vector< unique_ptr< statement > > && statements ) m_statements( std::move(statements) ) { }
Comments
Post a Comment