如何从函数返回无法更改的值?
How can i return from a function a value that just can't be changed?
我知道函数可以返回const引用,但有其他方法可以实现这种行为吗?意思是,我想返回一个不能修改的值。
#include <string>
#include <iostream>
using namespace std;
class A {
public:
A( int x, int y): _x(x), _y(y) {};
int _x;
int _y;
};
const A genObjA()
{
return A( 0,0 );
}
int main(int argc, char **argv) {
A new_obj = genObjA();
std::cout << new_obj._x;
new_obj._x = 10; // user can change new_obj
std::cout << new_obj._x;
}
这将打印
0
10
您不必返回const引用,您可以返回const对象。
const Object function_name() {
// ...
}
您不修改返回值,而是修改它的副本。在这个代码中,您不能执行genObjA()._x=10;
。
为了达到你的目标,你可以写额外的类:
class A_const{
protected:
int _x;
int _y;
operator=(const A_base&)=default;
public:
A()=default;
A(const A_base&)=default;
A( int x, int y): _x(x), _y(y) {};
int x(){return _x;}
int y(){return _y;}
//or
int get_x(){return _x;}
int get_y(){return _y;}
};
class A {
public:
using A_const::A_const;
A(const A&)=default;
int& x(){return _x;}
int& y(){return _y;}
//or
int& set_x(int val){return _x=val;}
int& set_y(int val){return _y=val;}
};
const A_const genObjA_const(){
return A_const(0, 0);
}
如果你想要一个防傻的修改保护,你可以使用PIMPL习惯用法。
然而,如果你对与你班一起工作的同事的理智有合理的信心,只需使用const参考。如果你想确定,记录下为什么你不想修改对象的原因,这样你的同伴就可以跟随你的想法(并得出同样的结论)。PIMPL成语试图把你从坚定的傻瓜手中拯救出来。但是意志坚定的傻瓜甚至会围绕PIMPL工作,所以在尝试中弄乱代码没有什么意义。
相关文章:
- 从函数返回const char*数组
- 检查函数返回类型是否与STL容器类型值相同
- 从 c 或 cpp 系列子函数返回到主函数
- 从函数返回任意简单类型的数据
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 从 C++ 中的函数返回数组地址问题
- VirtDisk.h QueryChangesVirtualDisk() 函数返回 RangeCount 为 0
- 为什么glGetSubroutineIndex为不同的函数返回相同的值?
- 在 c++ 中将函数返回类型指定为模板参数
- 从封装在对象中的函数 C++ 返回时为空的列表
- 为什么向量内部的指针在从函数返回时会发生变化?
- 函数返回的 rvalue 引用(表达式)是 xvalue - 但没有标识?
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 寿命延长从函数返回引用
- 程序不向函数返回值
- 字符串函数返回奇怪的值
- 类的大问题,以及从空函数c++返回
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- C++二叉搜索树模板从函数返回节点
- NVCC 错误:string_view.h:constexpr 函数返回是非常量