Call a constructor or allocate an object in-place

Since I joined Dell, my main field of research and work has somewhat changed. Now I am mostly working with C++ and file-systems. This world is not entirely new to me, but apparently I have a lot of stuff to learn.

Today I’d like to talk about one nice trick that I learned few days ago.

When working with large software systems, memory management becomes an imperative. In C, you can easily allocate a large chunk of memory and allocate structure right on that buffer. This is by far more difficult in C++, because compiler has to call consturctor.

Apparently, you can, in a way, directly call object’s constructor . I.e. you can allocate an object, on specified memory region, without actually allocating this region.

This is how you do it.

char* s = new char[1024];

SomeClass* p = new (s) SomeClass;

First new operator just allocates 1024 bytes. This is good old allocation as we know it. Note the special syntax of the second new operator. It allocates the new object on memory specified in brackets. Basically, this calls SomeClass’s constructor using s as storage.

One thing that I don’t know how to do is how to call destructor on the object – i.e. how to delete an object in place.

Did you know that you can receive periodical updates with the latest articles that I write right into your email box? Alternatively, you subscribe to the RSS feed!

Want to know how? Check out
Subscribe page

7 Comments

  1. Alon says:

    To destroy an object created with a placement new, you explicitly call the object destructor, this is the only time when you are actually allowed to do that

  2. @Alon
    Cool. Exactly the bit I was missing. Thanks.

  3. Hander says:

    Hi Alex!

    Can you provide a more detailed example of this kind of allocation? I’ve found it very interesting, but i cannot see it’s use for…

    Thanks!
    Hander

  4. If you are really digging into c++, there are some great resources.

    The C++ faq lite has information on placement new and other core language features:
    http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10

    Scott Meyer’s Effective C++/Stl books are very good, and have similar information, but maybe better written.

    Josuttis’ book The C++ Standard Library is a must read for applications programming. If you are in kernel space, you may not be able to use the standard library though.

    Finally, the newsgroup comp.lang.c++.moderated is the very best place to ask questions. There tend to be a lot of language lawyers on that newsgroup who can answer even obscure questions, as long as you explain yourself clearly and provide example code.

  5. @Brendan Miller
    Thanks. I am familiar with most of these resources, but this is still very useful.

  6. @Hander
    One of the reasons is to ease memory management. It is much easier to allocate large pools of memory and then allocate objects on the pool.

Leave a Reply


three × = 3