36

Unlike new and delete operators malloc does not call the constructor when an object is created. In that case how must we create an object so that the constructor will also be called.

ckv
  • 10,125
  • 19
  • 96
  • 139
  • possible duplicate of [Malloc function in C++](http://stackoverflow.com/questions/2740939/malloc-function-in-c) – sbi Jun 08 '10 at 06:42
  • 2
    Just for the record, I can see legitimate reasons why you wouldn't call new/delete. For example, you might need to allocate your objects from a special memory pool. – Edward Falk Apr 06 '18 at 19:04

7 Answers7

81

Er...use new? That's kind of the point. You can also call the constructor explicitly, but there's little reason to do it that way

Using new/delete normally:

A* a = new A();

delete a;

Calling the constructor/destructor explicitly ("placement new"):

A* a = (A*)malloc(sizeof(A));
new (a) A();

a->~A();
free(a);
Michael Mrozek
  • 161,243
  • 28
  • 165
  • 171
  • 18
    You should also mention that you need to call the destructor explicitly when using placement new, and not use 'delete' to destroy it. – Rudi Jun 08 '10 at 06:34
  • @MichaelMrozek I tried to do a->A(); the same way you called destructor, just to see if that works instead of doing new (a) A() to call constructor , but I get error : error: invalid use of 'A::A' .. is there any reason why this does not work, because it seemed more natural to me – solti Jul 17 '16 at 03:08
  • 1
    There are usecases. Lua, for example, only allows you to put individual metadata tables on "heavy" userdata, which means it has to allocate it and free it. It does, however, give you the ability to destruct it before it frees the memory. Since Lua uses malloc and free (it's in C), this definitely has a use-case. – Qix - MONICA WAS MISTREATED Jul 10 '17 at 05:36
  • Another use case that I can think of is object pooling. – Travis Vroman Apr 18 '20 at 01:55
17

You can use "placement new" syntax to do that if you really, really need to:

MyClassName* foo = new(pointer) MyClassName();

where pointer is a pointer to an allocated memory location large enough to hold an instance of your object.

warrenm
  • 29,905
  • 6
  • 84
  • 110
  • 2
    `foo` and `pointer` may be of different types, or `pointer` may be an expression that calculates an offset into a larger block of memory. – warrenm Jun 08 '10 at 06:10
  • 3
    @RSamuel: I usually do it that way in the rare occasion I need placement new. I make sure I treat `pointer` as just memory and get an object through `new`. It also "hides" the cast. – GManNickG Jun 08 '10 at 06:15
  • @warrenm In the case where it is an offset into a memory block or the start of a memory block that was not allocated with malloc or new, it should be mentioned that pointer has to be properly aligned to hold the object. If it will not be aligned, accessing its primitive members (or the inner objects primitive members) may give a hardware exception on some hardware architectures and will result in slower access in other hardware architectures. – selalerer May 31 '12 at 17:15
6

Prefer new.

But if for some reason you have raw memory, you can construct it with "placement new":

new (ptr) TYPE(args);

And since you won't be using delete, you'll need to call the destructor directly:

ptr->~TYPE();
R Samuel Klatchko
  • 72,827
  • 15
  • 131
  • 185
5

You mis-understand what malloc does. malloc does not create objects, it allocates memory. As it does not create objects there is no object for it to call a constructor to create.

If you need to dynamically create an object in C++ you need to use some form of new.

CB Bailey
  • 700,257
  • 99
  • 619
  • 646
4

Use placement new. The advice is handy:

ADVICE: Don't use this "placement new" syntax unless you have to. Use it only when you really care that an object is placed at a particular location in memory. For example, when your hardware has a memory-mapped I/O timer device, and you want to place a Clock object at that memory location.

Igor Zevaka
  • 71,876
  • 26
  • 107
  • 127
3

Take a look at placement new operator, which constructs an object on a pre-allocated buffer.

Alex F
  • 40,884
  • 40
  • 141
  • 206
-5
class A
{
    public:
      A() { printf("Constructor of A"); }
};

int main()
{
   A* pA = (A*) malloc(sizeof(A));  // Construtor is not going to be called.

   __asm { MOV EAX, pA}             // Makes pA as "this" pointer in intel based s/m.

   A();                             // Calling constructor explicitly.

   return 0;
}
  • 2
    Your "explicit constructor call" creates a temporary object, which is immediately destroyed. It does NOT construct an object at `pA`. – Ben Voigt Oct 11 '11 at 05:10
  • 1
    I have no idea if this works and I can't imagine when this would useful. The existing answers show how to do this using a documented language feature. – Blastfurnace Oct 11 '11 at 05:13