Like Tree2Likes
  • 2 Post By Elkvis

Returning reference of vector

This is a discussion on Returning reference of vector within the C++ Programming forums, part of the General Programming Boards category; Example code: Code: #include <iostream> #include <vector> using namespace std; class A{ private: vector<int> v; public: A() { for(size_t i ...

  1. #1
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,681

    Returning reference of vector

    Example code:
    Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    class A{
    private:
        vector<int> v;
    public:
        A() { for(size_t i = 0 ; i < 4 ; ++i) v.push_back(i); }
        vector<int>& getV() {return v;}
    };
    
    int main()
    {
        A a;
        vector<int> foo = a.getV();
        
        return 0;
    }
    I read somewhere, that we can imagine the reference as a pointer to the vector.
    So, my question is:
    Let's assume that instance of class A, named a, was created with new. We call a.getV() to foo and then we call the destructor of a.
    foo is safe? Is the copy constructor of std::vector called?
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    2,388
    your main() function is making a copy of the vector inside the class, so in this case it would be perfectly safe. if you're storing a reference:

    Code:
    vector<int>& foo = a.getV();
    then you need to remember that it becomes invalid the instant you delete the object.
    Elysia and iMalc like this.
    Code:
    namespace life
    {
        const bool change = true;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Returning by reference
    By cuo741 in forum C++ Programming
    Replies: 1
    Last Post: 12-09-2010, 06:06 AM
  2. returning by reference / value.
    By Kitt3n in forum C++ Programming
    Replies: 4
    Last Post: 05-28-2010, 12:02 PM
  3. returning reference
    By l2u in forum C++ Programming
    Replies: 34
    Last Post: 04-17-2008, 11:29 AM
  4. Returning a reference? Why?
    By Mr_Miguel in forum C++ Programming
    Replies: 12
    Last Post: 09-13-2007, 11:43 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21