Reputation: 299
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
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
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
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
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