Re: vector return by value: on stack?
LR a 9crit :
NewLine wrote:
Hi
If I have a function:
std::vector<int> my_rbv()
{
std::vector<int> x;
// some stuff
return x;
}
will the returned vector arrive on the stack when this function gets
called?
I assume you are actually asking wether the vector elements will be put
on the stack.
That depends on your vector implementation. Some STL implementation may
allocate an initial vector<> object that can hold a limited number of
elements (let say 10) and then use the heap when the size exceeds it; I
would not expect it but it is possible.
Of course, it is possible that optimisations make that your
std::vector<int> x will never actually exists in the memory space.
Maybe.
For sake of argument, let's suppose it does.
I'm going to assume that you're concerned about the overhead associated
with placing a std::vector<> on the stack.
There's probably not much for that. The memory that a std::vector<>
uses when you add elements to it isn't allocated on the stack and AFAIK
the sizeof(std::vector<YourTypeHere>) will be constant.
sizeof() is computed at compile type so you can safely expect it to be
constant.
You might want to try this little piece of code for yourself.
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
for(int i=0; i<5; i++) {
std::cout << i << " " << sizeof(v) << " " <<
v.size() << std::endl;
v.push_back(100);
}
}
On my system, the output for this code is:
0 16 0
1 16 1
2 16 2
3 16 3
4 16 4
Which implies that if a std::vector<int> is returned on the stack it'll
take up 16 bytes on my system, no matter how many elements the
std::vector has.
I haven't taken a look at the standard, but I suspect much of this will
be implementation specific, so Your Mileage Will Almost Certainly Vary.
And as I suggested, there may be other mechanisms for returning the
value. You may want to search for "Name Return Value Optimization" or
similar.
NRVO is a compiler optimisation.
The compiler is free to do anything provided the execution present the
same behavior as guaranteed by the standard, the only thing you can do
it for such matters is test it for your plateform with your specific
version of compiler and with your specific set of compiler options.
Also, AFAIK I don't think there is a requirement for a C++
implementation to have a stack. At least not a hardware stack. Which
implies that there may other mechanisms for returning values from
functions.