NewLine said:
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?
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.
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.
I found this
http://blogs.msdn.com/slippman/archive/2004/02/03/66739.aspx article
about a particular implementation, so the compiler you use is almost
certain to differ in this regard.
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.
LR