1

Only objects (including arrays) of trivial type may be created by a call to std::malloc.

I read it from http://en.cppreference.com/w/cpp/types/is_trivial, under the Note section. So if I have a non-trivial type T, what will happen if I use std::malloc( sizeof(T) )?

user3156285
  • 353
  • 1
  • 3
  • 15

1 Answers1

3

std::malloc is just a "renaming" of old C (not C++) function malloc(3).

So if it succeeds, it malloc(sizeof(T)) returns a pointer to an uninitialized memory zone of the size needed by T

You need to call some constructor of T on that memory zone. You could use the placement new for that purpose, e.g:

 void* p = std::malloc(sizeof(T));
 if (!p) throw your_out_of_memory_exception();
 T* ptr = new(p) T(32);  /// placement new, with constructor called with 32

Actually many C++ implementations have their standard ::operator new doing something similar. (So new calls malloc !)

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547