向量< T> ::交换和临时对象 [英] vector<T>::swap and temporary object

查看:159
本文介绍了向量< T> ::交换和临时对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

#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);
}

为什么?

推荐答案

因为 vector< int>()是一个 rvalue (一个临时的,大致来说),并且您不能绑定一个非< - code> 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.

这篇关于向量&lt; T&gt; ::交换和临时对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆