简体   繁体   中英

Returning const reference from function

I want my function to return an array of objects. But i want some restriction on returned reference so that returned value/reference is not modified by caller.

Eg

class A
{
    B **arrB;

    public :
        A() 
        {
            initialize arrB 
        }
        B** getB()
        {
           return arrB;
        }
}

In above code, array returned by getB() function, should not be modified. Can someone suggest best way to do this ? Can "const" help?

this should do it:

const B * const * getB() const { return arrB; }

EDIT: added const since member function doesn't modify contents.

Yes it will help. But then you will get an error about illegal conversion from B ** to const B ** , but that is the reason for const_cast :

const B** getB() const
{
    return const_cast<const B**>(arrB);
}

Note that I added an extra const qualifier after the function declaration. This tells the compiler that the function does not modify anything in the class.

const doesn't really help. The compiler may raise some warnings/errors when you try to modify the array, but you can always cast to a non- const pointer and modify it. const is more a hint to the user of the class: the pointer I'm giving you you is read-only; modify it at your peril!

Well, the possible way I see is to return new array copied from the private one (containing copies of original object instances). If you want to be sure the private member of the class is not changed you then need not to care about what the code which takes the copy of arrB pointer will do with it. But of course there are disadvantages like more memory usage and that the consumer has to delete obtained array.

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