13

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
Chris Masterton
  • 2,197
  • 4
  • 24
  • 30

1 Answers1

20

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

#include <new>

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

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • 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 Oct 11 '10 at 22:39
  • @Chris: Yup. It's easy to forget about these little headers because they're often included by other ones that are almost always included. – GManNickG Oct 11 '10 at 22:40
  • 4
    Including `` 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. – Cheers and hth. - Alf Oct 11 '10 at 22:51
  • @Alf: Fair, though I doubt circumventing a member `operator new` is the best intention. – GManNickG Oct 12 '10 at 00:20