std :: std :: shared_ptr用法的向量

Baz*_*Baz 2 c++ visual-studio-2010

以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

在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.
Run Code Online (Sandbox Code Playgroud)

从Something中删除析构函数,错误消失,为什么会出现此错误?

更新:

后来我会有类似的东西:

Something* s = new Something[100];
Run Code Online (Sandbox Code Playgroud)

并且各个共享指针将被传递给其他对象

For*_*veR 6

Something* s = new Something[1]; // raw pointer received from C api
std::shared_ptr<Something> p = std::shared_ptr<Something>(s); 
Run Code Online (Sandbox Code Playgroud)

是不正确的用法,因为

~shared_ptr();
Run Code Online (Sandbox Code Playgroud)

效果: - 如果*为空或与另一个shared_ptr实例共享所有权(use_count()> 1),则没有副作用.

- 否则,如果*拥有对象p和删除器d,则调用d(p).

- 否则,*它拥有一个指针p,并调用delete p.

默认删除器是operator delete,但是您已经Something* s = new Something[1];使用array-new运算符分配,应该使用array-delete运算符(delete [])删除,否则它是未定义的行为.例如,您应该使用特定的删除器构造shared_ptr,或者为数组使用某些东西boost::shared_array.

例如,这段代码是正确的.

template<typename T>
void deleter(T* p)
{
   delete[] p;
}

Something* s = new Something[1]; // raw pointer received from C api
std::shared_ptr<Something> p = std::shared_ptr<Something>(s, deleter<Something>);
Run Code Online (Sandbox Code Playgroud)