开发者

Returning a const reference to vector of an object

I have 2 questions related to the same problem:

  1. How can I return a reference to a vector which belon开发者_StackOverflowgs 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 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 it to be 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.


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.


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)


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(); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜