I'm reading from here: http://www.cplusplus.com/reference/deque/deque/push_back/
for
void push_back (const value_type& val);
that val is a
Value to be copied (or moved) to the new element.
e.g. if val is an instance of a class, in which case does it get copied and in which it gets moved? What is the difference between the two cases?
Can you also please explain what different happens in each one of the following add_val1, add_val2 and add_val3 ?
#include <deque>
class Value
{
int member1;
int member2;
};
class ValuesContainer
{
private:
std::deque<Value> m_vals;
public:
void add_val1(const Value &val)
{
m_vals.push_back( val );
}
void add_val2(const Value val)
{
m_vals.push_back( val );
}
void add_val3(const Value &val)
{
m_vals.push_back( Value(val) );
}
};
int main()
{
return 0;
}
Thanks!
That reference is confusing you, because it is by default showing only the copying push_back
, and still talking about moving.
Since C++11, there are two push_back
s
void push_back( const T& value );
which always copiesvoid push_back( T&& value );
which always movesIf the value you are pushing back has a name, or is explicitly a T&
, then it will use the first, otherwise the second
void add_val1(const Value &val)
{
m_vals.push_back( val ); // copy
}
void add_val2(const Value val)
{
m_vals.push_back( val ); // copy
}
void add_val3(const Value &val)
{
m_vals.push_back( Value(val) ); // move the temporary that is a copy of val
}
extern Value make_value_somehow()
void add_val4()
{
m_vals.push_back( make_value_somehow() ); // move
}
extern Value& find_value_somehow()
void add_val5()
{
m_vals.push_back( find_value_somehow() ); // copy
}
void add_val6(Value val)
{
m_vals.push_back( val ); // copy
}
void add_val7(Value val)
{
m_vals.push_back( std::move(val) ); // move
}
void add_val8(const Value val)
{
// m_vals.push_back( std::move(val) ); // ill-formed, can't modify val
}
void add_val9(Value & val)
{
m_vals.push_back( std::move(val) ); // move, which will confuse people
}