0

Assume we create an object on stack as

class Test{

Test(int i) {i_=i;}
Test(std::vector<int> v) {v_=v;}

int i_;
std::vector<int> v_;
};

int main() {
Test a;
// how much memory is occupied/reserved now for a?
.
.
.
return 0;
}

How compiler determines the required size for "a", when it is not yet known which constructor is going to be called? I mean, how much memory is reserved on stack? what about if i used "new" for object creation?

My example is very simplified in order to transfer my point. The aim of my question is to understand better the meaning of object creation/initialization on stack/heap.

trincot
  • 317,000
  • 35
  • 244
  • 286
Denis
  • 91
  • 4
  • Why do you believe that the size of the object depends on which one of its constructor gets called? Can you give an example where the size of the resulting object winds up being different, depending on which one of its constructors gets called? You might be under the impression that a `sizeof` of some vector gives you a different value when the vector is empty, or has a few billion values? This is not true. – Sam Varshavchik Jun 23 '22 at 12:18
  • very related/ maybe dupe: https://stackoverflow.com/questions/55478523/how-does-stdvector-support-contiguous-memory-for-custom-objects-of-unknown-siz/55478808#55478808 – NathanOliver Jun 23 '22 at 12:24
  • 1
    C++ does not provide a "deep size" operator. You'd need to write your own function to calculate the deep size of the Test object. – Eljay Jun 23 '22 at 12:26
  • 2
    Every instance of a class has the same size; `sizeof(a) == sizeof(Test)`, and `sizeof(a.v) == sizeof(std::vector)`. – molbdnilo Jun 23 '22 at 13:13

1 Answers1

1

How compiler determines the required size for "a", when it is not yet known which constructor is going to be called?

This question hinges on two misunderstandings:

First, Test a; does call the default constructor. Next, the size of objects to be allocated on the stack is a constant: sizeof(Test). This size does not change when more elements are added to the vector member, because those elements to not contribute to the size of a Test, they are allocated dynamically on the heap.

what about if i used "new" for object creation?

No difference concerning the size of the object. sizeof(Test) is a compile time constant and does not change depending on how you create the object. Though with Test* p = new Test; you'll have only p on the stack and its size is sizeof(Test*), while the object is on the heap.

PS: Actually "heap" and "stack" are not terms used by the standard, but as they are so common I think its ok to use them here. More formally correct would be to talk about automatic and dynamic storage duration (https://en.cppreference.com/w/cpp/language/storage_duration).

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185