Reputation: 117
im new to c++ and i'm finding hard to understand some vector behaviours. I was trying to implement a function to return an array of int and i found many suggestions to use a vector like this:
vector<int> myFunc()
{
vector<int> myVector;
//add elements to vector here...
return myVector;
}
But from what i know 'myVector' is an object created on the stack, so isnt it going out of scope when the function end? when does its destructor get called? I know there are few other questions about returning vectors, but i need to clarify this specific point, hoping to not have duplicated a question.
Upvotes: 9
Views: 6824
Reputation: 53901
Yes because myVector
is allocated on the stack, as soon as the function returns, it goes out of scope. But in this case that's ok! Your function signature is
vector<int> myFunc()
which returns a copy of myVector
so it doesn't matter that it's going out of scope since it's already being copied for the return.
However if you changed it to something like
vector<int> & myFunc()
now your telling it not to copy myVector
and you'll have a problem called a dangling reference since myVector
will be destructed and you don't copy it but still try to use it.
Upvotes: 15
Reputation: 129464
It does go out of scope, but when you return a class or struct, the compiler automatically makes a copy for you, so that your receiving object is filled in with the content of the original object.
Similar to:
vector<int> a;
vector<int> b;
... fill in vector a with stuff ...
b = a;
Upvotes: 0
Reputation: 1
Your code returns a copy of the myVector
instance on the stack. So it's OK it goes out of scope and is deleted (after return).
Upvotes: 1