【问题标题】:What effect does const at the beginning of a non-member function declaration have?非成员函数声明开头的 const 有什么作用?
【发布时间】:2017-02-04 13:21:33
【问题描述】:

翻阅 MSDN,我遇到了另一条奇怪的线路:

// This function returns the constant string "fourth".
const string fourth() { return string("fourth"); }

完整的例子埋在这里:https://msdn.microsoft.com/en-us/library/dd293668.aspx 精炼到最低限度,它看起来像这样:

#include <iostream>

const int f() { return 0; }

int main() {
    std::cout << f() << std::endl;

    return 0;
}

其他一些具有不同返回类型的测试表明,Visual Studio 和 g++ 都在没有警告的情况下编译这样的行,但 const 限定符似乎对我可以对结果执行的操作没有影响。谁能提供一个重要的例子吗?

【问题讨论】:

标签: c++ constants function-declaration non-member-functions


【解决方案1】:

不能修改返回的对象

示例:

#include <string>
using namespace std;

const string foo(){return "123";}
string bar(){return "123";}

int main(){
    //foo().append("123"); //fail
    bar().append("123"); //fine
}

这和 const 变量差不多

#include <string>
using namespace std;

const string foo = "123";
string bar = "123";

int main(){
    //foo.append("123"); //fail
    bar.append("123"); //fine
}

【讨论】:

    【解决方案2】:

    它是返回类型的一部分。函数返回const stringconst int

    const int 的情况下,这与int 相比确实没有什么区别,因为您可以对int 返回值做的唯一事情就是将值复制到某处(事实上,标准明确指出const 在这里无效)。

    对于const string,它确实有所不同,因为类类型的返回值可以调用成员函数:

    fourth().erase(1);
    

    fourth()返回const string的情况下将无法编译,因为erase()不是const方法(它试图修改它被调用的string)。

    就我个人而言,我从不让返回值的函数返回 const 值,因为它不必要地限制了调用者(尽管有些人认为防止编写像 string s = fourth().erase(1); 这样的东西很有用)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 2011-11-23
      • 2011-05-22
      • 1970-01-01
      • 2015-06-03
      相关资源
      最近更新 更多