Take the 2-minute tour ×

I tried writing this class

#include <memory>

class ContainerUnique


    std::unique_ptr<UniqueElement> u;

Where UniqueElement is a POD class defined elsewhere. I now define the constructor body like this:

    auto tmp = new UniqueElement(1);

    this->u(tmp); // u is a unique_ptr<UniqueElement>. Should this call compile?

And it complies without exceptions. Running the program I find that after the constructor of ContainerUnique has been called, u contains a null pointer.

Is this the intended behaviour? And what unique_ptr method am I actually calling?

share|improve this question
Not sure about the problems you are encountering. But avoid them by initializing the member variable u in the constructor's initialaztrion list. –  Anon Mail Jul 2 '12 at 14:28
Yes, that's the solution I used in my real code, but I'm still not sure about what is happening in the example. –  Coffee on Mars Jul 2 '12 at 14:30
Try printing the type of your auto variable. Not sure if typeid works. Once you know the type the rest should be easy. –  Anon Mail Jul 2 '12 at 14:34

3 Answers 3

up vote 19 down vote accepted

This is a known problem with VS2010's unique_ptr. It publicly inherits from its deleter if it's empty as an optimization (empty base optimization). The downside to the public inheritance is that all members of the deleter also become available members of unique_ptr, in this case its operator()(T*) that deletes the pointer.

The bug is fixed in VS2012's library where the inheritance is changed to private.

share|improve this answer
ah, you beat me to it. Good find. –  stijn Jul 2 '12 at 14:35

You are calling default_delete< UniqueElement >::operator () ( UniqueElement* ptr ), because uniqe_ptr derives from it (to benefit from empty base class optimization), and it deletes ptr. It's not exactly intended behavior for you, although I don't think the standard forbids it.

share|improve this answer

It should be done like

ContainerUnique::ContainerUnique(void):u(new UniqueElement(1)) {
share|improve this answer
This is the way I solved the problem in my production code, but I'm still unsure about what's happening in the example. –  Coffee on Mars Jul 2 '12 at 14:33

Your Answer


