简体   繁体   中英

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? 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 Object function_name() {
// ...
}

You don't modify returned value, you modify it's copy. In this code, you can't do 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.

However, if you have reasonable faith in the sanity of your coleagues who work with your class, just use a const-reference. 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. But determined fools will even work around PIMPL, so there's little point in messing up your code in the attempt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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