Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 809
user2591935 Avatar asked Oct 22 '14 11:10

user2591935


2 Answers

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.

like image 139
dau_sama Avatar answered Nov 15 '22 03:11

dau_sama


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.

like image 36
ForEveR Avatar answered Nov 15 '22 03:11

ForEveR