简体   繁体   English

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

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

I know a function can return a const reference, but are there other methods to achieve this kind of behavior? 我知道一个函数可以返回const引用,但是还有其他方法可以实现这种行为吗? Meaning, i want to return a value that just can't be modified. 意思是,我想返回一个无法修改的值。

#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;

}

This will print 这将打印

0
10

You don't have to return a const reference, you can return a const object. 您不必返回const引用,可以返回const对象。

const Object function_name() {
// ...
}

You don't modify returned value, you modify it's copy. 您不修改返回值,而是修改它的副本。 In this code, you can't do genObjA()._x=10; 在此代码中,您无法执行genObjA()._x=10; .

To reach your goal, you can write extra class: 为了实现您的目标,您可以编写额外的类:

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);
}

If you want a fool-proof modification safeguard, you can use the PIMPL idiom. 如果您想要一个简单的修改保护措施,则可以使用PIMPL习惯用法。

However, if you have reasonable faith in the sanity of your coleagues who work with your class, just use a const-reference. 但是,如果您对与您的班级一起工作的同事的理智有合理的信念,请使用const引用。 If you want to be sure, document the reason why you don't want the object to be modified, so that your fellows can follow your thoughts (and come to the same conclusion). 如果你想确保,说明为什么你不希望对象被修改,从而使你的同伴可以按照你的想法(并得出了相同的结论)的原因。 The PIMPL idiom tries to save you from the determined fools. PIMPL习惯用法试图将您从确定的傻瓜中解救出来。 But determined fools will even work around PIMPL, so there's little point in messing up your code in the attempt. 但是坚定的傻瓜甚至可以解决PIMPL,因此在尝试中弄乱代码毫无意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM