C ++私有指针“泄漏"? [英] C++ private pointer "leaking"?
问题描述
我将创建一个类来保存一长串将传递给函数的参数.让我们使用这个较短的示例:
I'm going to create a class to hold a long list of parameters that will be passed to a function. Let's use this shorter example:
class ParamList{
public:
ParamList(string& a_string);
string& getString(); //returns my_string
private:
string& my_string;
}
我的问题是这样的:my_string是私有的,但我正在返回对其的引用.这不是在C ++中称为私有指针泄漏之类的东西吗?这不是好的编程习惯吗?我希望getString的调用者能够获取引用并对其进行修改.
My question is this: my_string is private, yet I'm returning the reference to it. Isn't that called something like private pointer leaking in C++? Is this not good programming practice? I want callers of getString to be able to get the reference and also modify it.
请让我知道.
谢谢, 杰布
edit1:调用者将使用getString()并修改返回的字符串.
edit1: callers will use getString() and modify the string that was returned.
推荐答案
只要满足以下条件,恢复私有引用就可以了:
Returing a private reference is perfectly okay so long as:
A.这是一个const
引用,并且您已记录了该引用何时可以无效或
B.该引用旨在进行修改(即std::vector<T>::operator[]
)
A. That is a const
reference, and you have documented when that reference can be invalidated or
B. That reference is intended to be modified (i.e. std::vector<T>::operator[]
)
虽然在返回非常量引用的情况下很有用,但通常应避免使用它. Scott Meyers的有效C ++ (第三版,条款28):如果您想看一下,请避免将句柄"返回给对象内部.
While there are useful cases for returning a non-const reference you should usually avoid it. This is covered in Scott Meyers' Effective C++ (3rd Edition, Item 28): Avoid returning "handles" to object internals, if you'd like to take a look.
这篇关于C ++私有指针“泄漏"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!