vector::交换和临时对象
代码如下:
#include <vector>
int main()
{
vector<int> v1(5,1);
v1.swap(vector<int> ()); //try to swap v1 with a temporary vector object
}
上面的代码无法编译,错误:
error: no matching function for call to ‘std::vector<int, std::allocator<int> >::swap(std::vector<int, std::allocator<int> >)’
但是,如果我将代码更改为这样,它可以编译:
int main()
{
vector<int> v1(5,1);
vector<int> ().swap(v1);
}
为什么?
Code goes below:
#include <vector>
int main()
{
vector<int> v1(5,1);
v1.swap(vector<int> ()); //try to swap v1 with a temporary vector object
}
The code above cannot compile, error:
error: no matching function for call to ‘std::vector<int, std::allocator<int> >::swap(std::vector<int, std::allocator<int> >)’
But, if I change the code to something like this, it can compile:
int main()
{
vector<int> v1(5,1);
vector<int> ().swap(v1);
}
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为
vector()
是一个 rvalue(粗略地说,是临时的),并且您不能将非 const 引用绑定到右值。因此在这种情况下,您不能将其传递给采用非 const 引用的函数。但是,在临时变量上调用成员函数是完全可以的,这就是第二个示例可以编译的原因。
Because
vector<int>()
is an rvalue (a temporary, roughly speaking), and you cannot bind a non-const
reference to an rvalue. So in this case, you cannot pass it to a function taking a non-const
reference.However, it's perfectly fine to invoke member functions on temporaries, which is why your second example compiles.
调用().swap(v1) 在允许的 [non-const] 临时变量上调用非常量函数。
v1.swap(std::vector())
尝试将临时对象(即std::vector()
)绑定到非对象-常量引用。这是非法的并且失败的。另一方面,使用 std::vector在 C++2011 中,我本以为声明将更改为
std::vector::swap(T&&)
,因此使用就可以了swap() 与临时对象(但显然,仍然不与 const 对象)。正如 GMan 指出的那样,事实并非如此。
The call
v1.swap(std::vector<int>())
tries to bind a temporary (i.e.std::vector<int>()
) to a non-const reference. This is illegal and fails. On the other hand, usingstd::vector<int>().swap(v1)
calls a non-const function on the [non-const] temporary which is allowed.In C++2011 I would have thought that the declaration would be changed to
std::vector<T>::swap(T&&)
and it would thus become OK to useswap()
with temporaries (but, obviously, still not withconst
objects). As GMan pointed out this isn't the case.