C ++ private pointer "leak"?
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 question is this: my_string is private, but I am returning a reference to it. Isn't this called something like a personal pointer leaking in C ++? Isn't that good programming practice? I want the callers of getString to be able to get the reference and also change it.
Please let me know.
Thanks, JBU
edit1: Callers will use getString () and change the string that was returned.
source to share
Keeping a private link in order if:
and. This is a link const
and you registered when this link may be invalidated or
B. This link is intended to be modified (i.e. std::vector<T>::operator[]
)
While there are useful cases for returning a non-const reference, you should generally avoid it. This is documented in Effective C ++ by Scott Meyers (3rd Edition, Article 28): Avoid returning "descriptors" to internal objects, if you like.
source to share
First of all, you need to decide whether the ParamList will own the string or just "know about it". The way you wrote it with string& my_string
means it just has a descriptor for some other string. In this case, it is not (much of) a problem for some to change the string as the ParamList does not own it in the first place!
If you want the ParamList to have a complete master copy of the parameters (depending on the problem you are trying to solve), follow these steps:
class ParamList{
public:
ParamList(const string& a_string); // do a strcpy in here.
const string& getString(); //returns my_string
void setString(const string& new_string); //do a strcpy here too.
private:
string my_string;
}
Note that it is probably best to use the set and get functions anyway rather than returning a non-const reference, so the ParamList can have a little bit of control over its members.
source to share