带有函数签名的Const关键字

时间:2016-04-23 08:29:18

标签: c++ function stl const

这是我的简单代码:

#include <iostream>

using namespace std;

class alloc { };

template <typename T, typename Alloc = alloc>
class vector
{
public:
    void swap(vector<T,Alloc> &v) { cout << "swap()" << endl; }
};


template <typename T, typename Alloc>
void swap(const vector<T,Alloc> &v1,const vector<T,Alloc> &v2)
{
    v1.swap(v2);
}

int main()
{
    vector<int> x;
    vector<int> y;

    swap(x,y);

    return 0;
}

代码段运行没有问题。但我无法获得任何输出

然后我删除const关键字。

void swap(vector<T,Alloc> &v1,vector<T,Alloc> &v2)

我得到输出swap()

我已阅读&#34;原因是参数的const仅在函数中本地应用,因为它正在处理数据的副本。这意味着功能签名无论如何都是一样的。&#34;

所以我认为写或不写const没有区别。如果我坚持在这里写const,我如何修改代码以获得输出swap()

1 个答案:

答案 0 :(得分:7)

这是为什么应该避免using std的一个很好的例子。

要调试此问题,请删除using std,然后在需要标准库行为的位置添加std::。幸运的是,只有一个这样的地方,即模板类中的swap函数:

void swap(vector<T,Alloc> &v) { std::cout << "swap()" << std::endl; }

现在尝试再次编译到see the error,以防止swap使用const

  

prog.cpp:19:5:错误:传递const vector<int>作为this参数丢弃限定符

当您的计划为using std时,当您的功能不适用时,C ++可以选择std::swap替换swap个功能。这正是它所做的,没有任何警告,因为它假设它是你想要它做的。

该错误还告诉您如何做出const - 接受合格的向量:将const添加到vector::swap的参数中,如下所示:

void swap(const vector<T,Alloc> &v) const { std::cout << "swap()" << std::endl; }

现在你的程序编译并再次运行(demo)。

相关问题