joel
joel

Reputation: 7867

Does `new` allocate enough memory for any instance?

If I create a Foo with

Foo* foo = new Foo();

then reassign that foo

Foo mkfoo();

*foo = mkfoo();

Can I be sure that I've allocated enough memory for this new instance created by mkfoo? Even if Foo has dynamically-sized contents e.g. a std::vector which has different contents when created with mkfoo() than when created with new Foo()? If not, what's the best way to allocate the memory?

Upvotes: 1

Views: 144

Answers (2)

user17732522
user17732522

Reputation: 76678

The line

*foo = mkfoo();

does not create a new Foo object in the storage returned from new. It simply calls the assignment operator overload on the already present Foo object.

Even if you use e.g. a placement-new to actually create a new Foo object in the storage returned by the original new expression, that is fine, since objects of the same type always have the same object size (sizeof) determining the storage size they take up.

If you have a container such as std::vector<int>, its own object size (sizeof) is also always the same. However it will contain e.g. a pointer to other memory where the elements of the vector are stored (how exactly that is done is an implementation-detail). If you call .size() on a std::vector you don't get the size of the std::vector object, but the number of elements stored by the vector, which are however not stored in the std::vector object's memory itself and so don't count towards its object size.

Upvotes: 3

0x5453
0x5453

Reputation: 13589

Yes. Part of the definition of a "complete type" is that its size is known.

For types that contain dynamically-sized members like std::vector, the dynamic storage of those members is also allocated on the heap, so the size of that storage is not part of the calculation when considering the sizeof the object.

Upvotes: 4

Related Questions