views:

190

answers:

2

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  A: 

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.

David
"Do a strcpy"???
anon
@Neil: shorthand for "copy from one string to the other".
David
@David Name of function in standard library - possibility for confusion: high.
anon
@Neil: Not to mention it's as simple as `my_string = new_string`.
GMan
+3  A: 

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.

Billy ONeal