Reputation: 91
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.
Upvotes: 0
Views: 472
Reputation: 122350
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).
Upvotes: 1