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.
Yes because
myVectoris 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 iswhich returns a copy of
myVectorso 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
now your telling it not to copy
myVectorand you’ll have a problem called a dangling reference sincemyVectorwill be destructed and you don’t copy it but still try to use it.