-1

I am trying to do some work with my class and std::vector. I encountered with folloing problem,=

Here is my code:

class A
{
    private:
        ........
    public:
        vector<int>* ret_vec();
};

vector<int>* A::ret_vec()
{
    vector<int> vec;         // vec is declared as a local variable
    ......
    return &vec;
}

int main()
{
    .....
    vector<int>* vec = A.ret_vec();       // size of vec is 0 !!!
}

As you can see in the code, vec in vector<int>* A::ret_vec() is declared as a local variable, and when I assgin it to a pointer in main, the size of vec is 0.

Thus, I used following method instead:

class A
{
    private:
        vector<int> vec;         // vec is declared as a member variable
    public:
        vector<int>* ret_vec();
};

vector<int>* A::ret_vec()
{
    ......
    return &vec;
}

int main()
{
    .....
    vector<int>* vec = A.ret_vec();       // size of vec is ok
}

Now, as I declare vec as a member variable, when I assign it to a local pointer in main, its size is exactly as I expected.

May I know why is this? Many thanks.

========================================================== EDIT:

I'm sorry i haven't explained myself clear at the first place. I am dealing with a large data set vec, and the time performance is my current priority. Thus I'm afraid that return vector by values is not an option.

ChangeMyName
  • 7,018
  • 14
  • 56
  • 93
  • Return the vector by value. Your compiler will probably use the move assignement operator. – Jiwan Aug 27 '13 at 09:37
  • 1
    @Jiwan maybe value semantics are not required here. – juanchopanza Aug 27 '13 at 09:38
  • You're lucky that it returned `0` in the first case, worse could've happened. – Uchia Itachi Aug 27 '13 at 09:39
  • Hence you expose the member (2nd example) please avoid pointers, use a reference (which is always valid, not null), instead. If a member would be a pointer and that pointer is never zero return *member (a reference) –  Aug 27 '13 at 09:52
  • For your reference check this http://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-a-c-programmer-should-know-ab – Uchia Itachi Aug 27 '13 at 09:54
  • Returning by value is not necessarily slower (see [Want Speed? Pass By Value](http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/)) and is definitely safer than your alternative. – Jonathan Wakely Aug 27 '13 at 10:00

2 Answers2

7

You return a dangling pointer and run into undefined behavior. It's not legal to return a pointer to a local automatic variable.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

You return a pointer to a local variable,which will be deleted after the function call. So returning pointer is not a good practice. Just return the object.

Ani
  • 42
  • 4