【问题标题】:swap not working with function as parameter交换不使用函数作为参数
【发布时间】:2018-01-25 10:29:17
【问题描述】:
#include <bits/stdc++.h>

using namespace std;

vector<int> func()
{
    vector<int> a(3,100);
    return a;
}

int main()
{
    vector<int> b(2,300);
    //b.swap(func());   /* why is this not working? */
    func().swap(b);  /* and why is this working? */
    return 0;
}

在上面的代码中,b.swap(func()) 没有编译。它给出了一个错误:

没有匹配函数调用‘std::vector >::swap(std::vector >)’
/usr/include/c++/4.4/bits/stl_vector.h:929:注意:候选者是:void std::vector<_tp _alloc>::swap(std::vector<_tp _alloc>&) [with _Tp = int, _Alloc = std::allocator]

但是,当写成 func().swap(b) 时,它会编译。

它们之间到底有什么区别?

【问题讨论】:

  • 你的函数返回一个rvalue,所以第一个版本不能工作。
  • 我认为这是一个有效的问题 - 为什么要投反对票?

标签: c++ vector stl allocator


【解决方案1】:

func() 返回一个临时对象(一个右值)。

std::vector::swap() 将非 const vector&amp; 引用作为输入:

void swap( vector& other );

临时对象不能绑定到非 const 引用(它可以绑定到 const 引用)。这就是b.swap(func()); 无法编译的原因。

可以在临时对象超出范围之前调用方法,并且可以将命名变量(左值)绑定到非常量引用。这就是 func().swap(b) 编译的原因。

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2011-09-14
    相关资源
    最近更新 更多