4
votes

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.

4
You cannot allocate or deallocate memory from the stack. Since a was declared on the stack, you cannot delete it, which is what your unique_ptr tries to do when it falls out of scope. - Cory Kramer
Out of interest, what were you trying to achieve here? - doctorlove
doctorlove -> Nothing, I am just trying things for learning purposes - user2591935
for learning purposes, the less you use the heap in C++ the better . - dau_sama

4 Answers

2
votes

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.

2
votes

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.

2
votes

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.

1
votes

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);