Thread: Returning reference of vector

  1. #1
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Nice, France

    Returning reference of vector

    Example code:
    #include <iostream>
    #include <vector>
    using namespace std;
    class A{
        vector<int> v;
        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
    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:

    vector<int>& foo = a.getV();
    then you need to remember that it becomes invalid the instant you delete the object.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

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, 07: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