C++ 使用std::unique_ptr会产生无效指针错误,这有什么不对?

C++ 使用std::unique_ptr会产生无效指针错误,这有什么不对?,c++,unique-ptr,C++,Unique Ptr,代码如下: 我在这里复制相同的代码: #include <iostream> #include <memory> using namespace std; class cA{ public: cA(){} ~cA(){} }; int main() { std::unique_ptr<cA> qq(new cA[200]); cout << "OK" << e

代码如下:

我在这里复制相同的代码:

#include <iostream>
#include <memory>

using namespace std;

class cA{
    public: 
    cA(){}
    ~cA(){}
};
int main()
{
    std::unique_ptr<cA> qq(new cA[200]);
    
    cout << "OK" << endl;

    return 0;
}
只是做新的,没有什么比这更有趣的了


为什么会出现无效指针错误?

您的代码有未定义的行为。您将
std::unique_ptr
指定为包含单个对象,但使用数组初始化它。 您应该将模板参数指定为数组;否则,
std::unique\u ptr
将尝试调用
delete
而不是
delete[]
来销毁对象并释放内存

std::unique_ptr<cA[]> qq(new cA[200]);
std::unique_ptr qq(新cA[200]);
std::unique_ptr<cA[]> qq(new cA[200]);