简体   繁体   English

从函数返回const引用

[英]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. 在上面的代码中,getB()函数返回的数组不应该被修改。 Can someone suggest best way to do this ? 有人可以提出最佳方法吗? Can "const" help? “const”可以帮助吗?

this should do it: 这应该这样做:

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

EDIT: added const since member function doesn't modify contents. 编辑:添加const因为成员函数不修改内容。

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 : 但是你会得到关于从B **const B **非法转换的错误,但这就是const_cast的原因:

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

Note that I added an extra const qualifier after the function declaration. 请注意,我在函数声明后添加了一个额外的const限定符。 This tells the compiler that the function does not modify anything in the class. 这告诉编译器该函数不会修改类中的任何内容。

const doesn't really help. const并没有真正帮助。 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指针并对其进行修改。 const is more a hint to the user of the class: the pointer I'm giving you you is read-only; const更像是对类的用户的一个提示:我给你的指针是只读的; 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. 如果你想确保类的私有成员没有被更改,那么你不必关心采用arrB指针副本的代码将用它做什么。 But of course there are disadvantages like more memory usage and that the consumer has to delete obtained array. 但是当然存在诸如更多内存使用以及消费者必须删除所获得的数组的缺点。

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

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