【问题标题】:Why can I not assign values to a shared pointer array?为什么我不能为共享指针数组赋值?
【发布时间】:2020-12-08 17:08:30
【问题描述】:

这个小例子给出了错误信息

Error   C2440   '=': cannot convert from '_Ux (*const )' to 'int *' Templ   1266
Error   C3692   non-scalar type 'int []' cannot be used in a pseudo-destructor expression

_Ux(*const) 是什么?

这是程序:

#include <memory>
int main()
{
    shared_ptr<int[]> as = make_shared<int[]>(10);
    for (int i = 0; i < 10; i++) {
        as[i] = i + 100;
    }
}

【问题讨论】:

  • 抱歉,使用了std 命名空间。
  • @RemyLebeau 在他的回答中也提到了可能对 c++20 的支持
  • 我使用 Visual Studio C++ 2019,语言标准 C++17。从shared_ptr 切换到unique_ptr 时,代码运行如图所示。

标签: c++ shared-ptr


【解决方案1】:

显示的代码无法编译,因为shared_ptrmake_shared()std 命名空间中,但是没有using namespace std; 语句,或者至少没有using std::shared_ptr;using std::make_shared; 语句。

但是,要解决这个问题,请确保您正在为 C++20 编译此代码,因为 std::make_shared() 不支持在早期版本中创建数组,这可能会导致您看到的错误。

在 C++17 中,您将不得不手动构造数组,但 std::shared_ptr 会正确释放数组,例如:

std::shared_ptr<int[]> as( new int[10] );

Live Demo

但是,std::shared_ptr 在 C++11 和 C++14 中根本不支持数组,因此您必须使用自定义删除器来正确释放数组,并使用 std::shared_ptr::get() 而不是 std::shared_ptr::operator[]访问数组元素,例如:

#include <memory>

int main()
{
    std::shared_ptr<int> as( new int[10], [](int *p) { delete[] p; } );
    for (int i = 0; i < 10; i++) {
        as.get()[i] = i + 100;
    }
}

对于动态数组,您应该考虑改用std::vector,例如:

#include <vector>

int main()
{
    std::vector<int> as(10);
    for (int i = 0; i < 10; i++) {
        as[i] = i + 100;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多