views:

67

answers:

1

Can I call the C++ placement new on constructors with parameters? I am implementing a custom allocator and want to avoid having to move functionality from non-default constructors into an init function.

class CFoo
{
public:
    int foo;
    CFoo()
    {
        foo = 0;
    }

    CFoo(int myFoo)
    {
        foo = myFoo;
    }
};

CFoo* foo = new (pChunkOfMemory) CFoo(42);

I would expect an object of type CFoo to be constructed at pChunkOfMemory using the second constructor. When using operator new am I stuck with default constructors only?

Solved! I did not #include <new>. After this, calling placement ::new worked fine with non-default constructors.

+7  A: 

To use placement new, you need to include the header <new>:

#include <new>

Otherwise the placement forms of operator new aren't defined.

GMan
Success! I cant believe I've been struggling with this all day and it was a missing include file. D'oh! Thanks GMan and aschelper.
Chris Masterton
@Chris: Yup. It's easy to forget about these little headers because they're often included by other ones that are almost always included.
GMan
Including `<new>` is the practical answer to the OP's question, but the information given in the first line above is incorrect. One does not need to icnlude `new`, but the relevant `operator new` allocation function must be defined (as a member or in the global namespace). To the OP: to be sure to use the global allocation function you should generally write `::new`, not just `new`, when using the "construct in place" placement new; otherwise you might pick up a member allocation function.
Alf P. Steinbach
@Alf: Fair, though I doubt circumventing a member `operator new` is the best intention.
GMan