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.
std::vector (for T other than bool) meets the requirements of Container, AllocatorAwareContainer, SequenceContainer, ContiguousContainer (since C++17) and ReversibleContainer. Member functions of std::vector are constexpr : it is possible to create and use std::vector objects in the evaluation of a constant expression.
Stack behavior with std::vector If the subscript operator and at () function are based on the array length, and the capacity is always at least as large as the array length, why even worry about the capacity at all? Although std::vector can be used as a dynamic array, it can also be used as a stack.
When a vector variable goes out of scope, it automatically deallocates the memory it controls (if necessary). This is not only handy (as you don’t have to do it yourself), it also helps prevent memory leaks. Consider the following snippet: If earlyExit is set to true, array will never be deallocated, and the memory will be leaked.
Unlike array subscripts or at (), the stack-based functions will resize the std::vector if necessary. In the example above, the vector gets resized 3 times (from a capacity of 0 to 1, 1 to 2, and 2 to 3). Because resizing the vector is expensive, we can tell the vector to allocate a certain amount of capacity up front using the reserve () function:
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With