我正在阅读这里: http://www.cplusplus.com/reference/deque/deque/push_back/
对于
void push_back (const value_type& val);
那个val是一个
Value to be copied (or moved) to the new element.
例如如果 val 是一个类的实例,在哪种情况下它会被复制并移动?这两种情况有什么区别?
能否请您解释一下以下 add_val1、add_val2 和 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;
}
谢谢!
最佳答案
该引用让您感到困惑,因为它默认显示仅 复制push_back
,并且仍在谈论移动。
从 C++11 开始,有两个 push_back
void push_back( const T& value );
总是复制void push_back( T&& value );
始终移动
如果你推回的值有一个名称,或者明确是一个T&
,那么它将使用第一个,否则使用第二个
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
}
关于c++ 当你在双端队列中 push_back 或 push_front 时真正发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47904213/