Bob5421
Bob5421

Reputation: 9073

where does a c++ function puts return value

Let's have a look to this code. I was thinking a c++ function only returns an int value in eax. So where does it store the vector result ? Heap ? Stack ?

Thanks

#include <iostream>
#include <vector>

using namespace std;


vector<int> fonction(int a)
{
        vector<int> vec;
        for (int i=0;i<a;i++)
        {
                vec.push_back(1);
        }
        return vec;
}

int main(int argc, char *argv[])
{
        cout << "test" << endl;
        auto res = fonction(10);
        cout << res.size() << endl;
        return 0;
}

Upvotes: 0

Views: 229

Answers (2)

Serge
Serge

Reputation: 12354

looks like gcc forx86_64allocates return vector struct on stack of the caller and returns a pointer to it in rax.

movq    -48(%rbp), %rax
...
ret

Upvotes: 0

Curious
Curious

Reputation: 21510

As far as registers go the C++ standard does not specify which registers should contain the value, since the standard is not dependent on architectures. It just defines the syntax and semantics of the language

As for what happens when you create the vector in your function, the contents of the vector are stored on the heap (as usual) and the vector itself (i.e. the pointer and other bookkeeping) is stored in the stack frame of the function.

And when you go to return the vector from the function by value, the return value is treated as an rvalue, and that rvalue is guaranteed to be moved into the vector (i.e. the pointer and other bookkeeping) that has been allocated in main.

Note that there is something called NRVO, which if the compiler is able to apply. There is no moving, the value is simply taken from the stack of the function and put where it needs to go.


okay, is it correct to return a vector type from a function ?

Absolutely, it's completely fine

Upvotes: 2

Related Questions