Home > Enterprise >  Does `new` allocate enough memory for any instance?
Does `new` allocate enough memory for any instance?

Time:01-07

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?

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • Related