views:

657

answers:

3

Hi there,

I have 2 questions related to the same problem:

1) How to return a reference to a vector which belongs to a class. I have this class:

class sys{
  protected:
    vector<int> s;

  public:
    sys();
    vector<int>& getS() {return s;} //(1)
};

(1) should return the reference of the vector s. However in the main:

main(){
  sys* my_sys = new sys();
  vector<int> &t1  = my_sys->getS(); //(2)
  vector<int> t2 = my_sys->getS(); //(3)
  ...
}

t1 is a reference to s (i.e. when t1 is changed my_sys.s is changed as well). t2 is a COPY of s (i.e. when t2 is changed my_sys.s is NOT changed). Why does line (3) work?

2) I do not want that it is possible to change my_sys.s outside of the class, but I want to return a reference because of efficiency. Where do I put the const? I tried to change line (1) to

const vector<int>& getS() {return s;} //(4)

but I am not sure if that is enough.

Thanks for your help.

+1  A: 

Line (3)

For the int type it is trivial to copy. If you put objects in there and they have a Copy CTor, this will also work.

Line (4)

Make it

const vector<int>& getS() const {return s;}

so the function is also declared as const.
And call it like this

const vector<int> & t1 = my_sys->getS();
mxp
+4  A: 

Line 3 works because t2 is copy-constructed from the reference returned by getS()

The way you const-qualify the reference returned by getS() is OK. You could const-qualify getS() as well, i.e.:

const vector<int>& getS()const;

so that getS() could be called on a const sys.

Éric Malenfant
+1  A: 

Line 3 works because c++ calls the copy constructor on the vector.

Your function returns a reference, that reference is passed to the vector copy constructor and your variable t2 is constructed.

This is allowed as the copy constructor of vector is not defined as explicit.

You cannot guard against this with a general type. In your own class you can mark the copy constructor explicit and the assignment would fail.

You could return a const pointer instead. This would guard against the copy - but might be dangerous as users may expect to be able to pass the pointer beyond its valid scope.

const vector<int>* getS() {return &s;} //(4)
morechilli
I don't think the const pointer helps, just makes it slightly less convenient. vector<int> cv = *getS();will make a copy of the vector.
KeithB
morechilli