有两个 std::vector::push_back
声明。我在某种程度上理解 rvalue
和 lvalue
。据我所知,几乎所有类型(T&、T&&、T
)都可以转换为const T&
,所以当不同类型的对象传递时,编译器会选择哪一种到 std::vector::push
?
我是C++新手。虽然我想了一遍又一遍,但我还是不明白。如果你能给我一些简单的例子来让我明白就更好了。如果你能得到一些帮助,我将不胜感激带着这个问题。
根据文档( http://www.cplusplus.com/reference/vector/vector/push_back/ ),其中表示:
void push_back (const value_type& val);
void push_back (value_type&& val);
Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.
最佳答案
左值无法绑定(bind)到右值引用,这意味着当您调用 std::vector<T>::push_back
时对于左值参数,唯一可行的重载是 const T&
参数。
右值可以绑定(bind)到右值引用和const左值引用。因此,两种重载都适用。但根据C++重载规则,右值引用参数T&&
的重载将被选中。
您可以轻松地自己尝试一下:
void f(const int&) { std::cout << "L"; }
void f(int&&) { std::cout << "R"; }
int main()
{
int i = 0;
f(i); // prints "L"
f(0); // prints "R"
}
关于c++ - 关于 `std::vector::push_back`声明的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62208923/