【发布时间】:2017-06-08 09:14:40
【问题描述】:
我的印象是,通过声明返回类型const,可以防止数据结构被修改。但是,我对此进行了测试,并且可以修改数据结构。这是为什么呢?
例如,以下代码在使用--std=c++11 编译时打印1 2 3 4 5 6:
#include <iostream>
#include <set>
using namespace std;
const set<int> f(void) {
set<int> s = {1, 2, 3, 4, 5};
return s;
}
int main(void) {
set<int> s = f();
s.insert(6);
for (auto elem: s) {
cout << elem << " ";
}
return 0;
}
【问题讨论】:
-
s是函数返回的集合的副本,它没有声明为const。 -
Const 非引用返回类型并不是真正有用。参见:stackoverflow.com/questions/6299967/… 另见:stackoverflow.com/questions/8716330/…
标签: c++ constants return-value return-type