tags:

views:

117

answers:

3

I have a class in c++ a portion of which is below

class Node{
    public:
       vector<string> getNames() const;
    private:
        vector<string> names_;
};
vector<string> Node::getNames(){
    return names_;
}

the function getNames() passes a copy of the vector. How can i modify my class so that i can reference the vector 'by const reference' from any other class that i declare the Node object instead of passing a copy?

+1  A: 

Change the definition to

const vector<string>& getNames() const;
Igor Krivokon
That should be marked as const.
GMan
Yes, thanks, fixed.
Igor Krivokon
+6  A: 

Try this:

class Node
{
    public:
       const vector<string>& getNames() const;

    private:
        vector<string> names_;
};

const vector<string>& Node::getNames() const
{
    return names_;
}

Few things:

  1. getNames() is now a const method, because the Node does not logically change.
  2. Return as a constant reference, so you don't make a copy.
GMan
A: 
Nikolai N Fetissov
Any client that const-casts something away is asking for crap, I don't see how that applies here. Same with string a reference. I welcome programmers to do stupid things then blame me, so I can have a good laugh.This is not premature, this is just good principle; don't make a potentially huge copy if you don't need to.
GMan
Storing a reference*
GMan
That's true, though sometimes there are advantages to returning a copy too.
Nikolai N Fetissov