如何从函数返回无法更改的值?

How can i return from a function a value that just can't be changed?

本文关键字:函数 返回      更新时间:2023-10-16

我知道函数可以返回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工作,所以在尝试中弄乱代码没有什么意义。