Captain Jack sparrow Captain Jack sparrow - 1 year ago 69
C++ Question

are objects allocated without using "new" allocated on stack or heap

I am new to c++ so question would be elementary.

Lets say I have defined a class Foo and I create a vector of vectors in the following code:

namespace testme {
class Foo {
Foo(int x): x_(x) { };
static vector<vector<int>> ReturnVecOfInts(int num) {
vector<vector<int>> ret(num);
for (int i = 0; i < num; i++) {
vector<int> tmp;
return ret;

When i call:


Is the vector of vectors created on heap or the stack. The reference is on the stack but I want to know whether it points to the heap since i want to return this object from a function.

This is important to me because clearly if these are allocated on the stack the vector of vectors would go out of scope and not usable outside the called function.

Answer Source

You're probably overthinking.

In your case, you're safe in code like this:

Foo f = Bar::GetFoo();

When you return objects from functions, in general, there may occur various optimizations (e.g. RVO, NRVO, etc.), but the bottom line is that your f object is safe to use.

Even if inside Foo you have a data member like std::vector which usually allocates its memory from the heap (you can customize this behavior using custom allocators), thanks to copy constructors, move constructors, destructor, etc. you are totally safe in returning it from functions, or copying Foo instances around.

EDIT I noted that you changed your code after I wrote my answer, returning a vector<vector<int>> instead of Foo. Again, what I wrote still applies.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download