简体   繁体   中英

How to default-initialize without using new?

I am trying to implement my own std::vector container, and I am using realloc() to resize it, to prevent deletion and reallocation every time. With the following code:

buffer = new T[n]();

This would default initialize each element of the array, and allow me to start accessing them right away. However, since the standard specifies that the memory must be previously allocated by malloc(), calloc() or realloc() to use realloc() , I cannot use new .

I know that calloc() will zero-initialize the memory, but I am not sure if that will have the same behavior as new T[n]() . What is the proper way to default-intialize with C style memory allocation?

First, no, zero-initializing memory is not the same as calling default constructors for the objects that that memory is supposed to hold. You have to call constructors. So malloc versus calloc doesn't matter in terms of correctness; so if you're going to go that route, use malloc -- it's faster.

Second, realloc won't work directly, because it doesn't know how to copy objects. Some objects can be copied byte-by-byte, and for those types, realloc is okay. But for most types, copying involves additional operations, and you have to use the copy constructor or copy assignment operator to do the copy. So realloc can be used in special cases, but not in general.

So, you're really limited to malloc and free , along with constructors (through placement new ) and destructors.

You can call any constructor with any kind of memory using this syntax:

::new (ptr) T(...arguments go here (if any)...);

You may have to use

#include <new>

It will call the constructor of T for a memory allocated at ptr. for an array you will have to loop:

T* ptr=(T*)malloc(sizeof(T)*n);
for(int i=0;i<n;++i)
   ::new(ptr+i) T();

But with this, DO NOT CALL delete ! You will have to explicitly call the destructor for each item and then free the memory with the correct function:

for(int i=0;i<n;++i)
   (ptr+i)->~T();
free(ptr);

In case of realloc, you must be sure that the T object can be relocated without any problem (byte-to-byte copy OK). It should be safe for struct with simple data type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM