user2591935
user2591935

Reputation: 299

unique ptr initialisation assertion failure

This causes my program to have an assertion failure:

int a = 5;
std::unique_ptr<int>intptr(&a);

The error

File: f:\dd\vctools\crt\crtw32\misc\dbgdel.cpp

Line: 32

Expression : _BLOCK_TYPE_IS_VALID(pHead > nBlockUse)

It works well when I initialise it using "new" or " = make_unique (..)" but I'm curious to know why I can't initialise it by giving the adress of an existing variable.

Upvotes: 5

Views: 850

Answers (4)

dau_sama
dau_sama

Reputation: 4347

Variable a is on the stack, if you bind it to a unique_ptr, when the unique_ptr will go out of scope, it will call delete on a variable that can not be deleted.

basically you can't get ownership of an automatic storage variable, only a dynamic one.

Upvotes: 3

eerorika
eerorika

Reputation: 238311

You can initialize the unique_ptr to an automatic variable by using a custom deleter like this:

auto noop = [](int*){};
std::unique_ptr<int, decltype(noop)>intptr(&a, noop);

Just remember not to let the pointer escape the scope where the automatic variable lives.

But it probably doesn't make any sense to use unique_ptr here at all, so you might want to reconsider your approach.

Upvotes: 2

P0W
P0W

Reputation: 47784

You can use address only if you have some weird custom deleter that does nothing for actual destroying.

struct D{

    void operator()(int* p) const {
        std::cout << "Deleter \n";
        //... no actual delete
    }
};  

int a =5;    
std::unique_ptr<int,D> intptr (&a);

Upvotes: 1

ForEveR
ForEveR

Reputation: 55887

You can initialize. Error is in destruction of unique_ptr, since by default it delete owner pointer. You should create with new, or use customer deleter.

Upvotes: 2

Related Questions