C++ private pointer “leaking”?

2019-07-14 14:14发布

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, 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.

Please let me know.

Thanks, jbu

edit1: callers will use getString() and modify the string that was returned.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-14 14:37

Returing a private reference is perfectly okay so long as:

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[])

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.

查看更多
戒情不戒烟
3楼-- · 2019-07-14 14:49

First off, you need to decide if the ParamList is going to own the string or just "know about it". The way you've written it, with string& my_string, means that it just has a handle onto someone else's string. In that case, it's not (much of) a problem for some to modify the string since ParamList doesn't own it in the first place!

If you want ParamList to have a full master copy of the parameters (depends on the problem you're trying to solve), do something like this:

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's probably better to use set and get functions anyway rather than returning a non-const reference, just so ParamList can have a little more control over how its members are modified.

查看更多
登录 后发表回答