The following code:
class Something
{
public:
~Something()
{
}
};
int main()
{
Something* s = new Something[1]; // raw pointer received from C api
std::shared_ptr<Something> p = std::shared_ptr<Something>(s);
std::vector<std::shared_ptr<Something>> v(&p,&p+1);
return 0;
}
gives the following error in VS Express 2010:
---------------------------
Microsoft Visual C++ Debug Library
---------------------------
Debug Assertion Failed!
File: f:\dd\vctools\crt_bld\self_x86\crt\src\dbgdel.cpp
Line: 52
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
Remove the destructor from Something and the error disappears, Why do I get this error?
Update:
Later I will have something like:
Something* s = new Something[100];
and individual shared pointers will be passed around to other objects
is incorrect usage, since
Default deleter is
operator delete, but you haveSomething* s = new Something[1];allocated by array-new operator, that should be deleted with array-delete operator (delete[]), otherwise it’s undefined behaviour. You should construct shared_ptr with specific deleter, or use something for arrays, for exampleboost::shared_array.For example this code is correct.