将C数组名称视为原始指针并复制到shared_ptr

时间:2017-01-19 03:25:47

标签: c++ arrays pointers shared-ptr

鉴于数组名称被隐式转换为指针,如何将所述数组的位置复制到std :: shared_ptr?

#include <iostream>
#include <memory>

int main() {
    int arr[3] = {7, 8, 9};
    std::cout << arr[0] << std::endl; //-> 7

    std::shared_ptr<int> arr_ptr(arr); // Core dumped
    std::shared_ptr<int> arr_ptr(&arr[0]); // Core dumped

    std::cout << std::endl;
    return 0;
}

这让我感到困惑,因为规范中的原始指针有一个合法的构造函数:

template <class U> explicit shared_ptr (U* p);

为什么我不能为此数组位置创建shared_ptr?

价: http://www.cplusplus.com/reference/memory/shared_ptr/shared_ptr/

Thx Keith:^)

2 个答案:

答案 0 :(得分:2)

arr在堆栈上静态分配,而不是new动态分配。一旦共享指针退出作用域,它将尝试在该指针上调用delete。由于指针引用未使用new分配的内存,因此结果未定义。

std::shared_ptr<>用于所有意图和目的用于管理内存的所有权,否则手动操作会很繁琐。在这种情况下,编译器使用堆栈帧自动管理内存。

答案 1 :(得分:2)

shared_ptr<>我们在C ++中称之为 RAII 。它拥有内存并在超出范围时尝试清理。

placement new的示例将解释此处发生的事情

int main()
{
    // Allocate memory in stack
    char memory[4];
    // use stack memory to allocate the intMem
    int *intMem = new (&memory) int;

    // delete the memory allocated in stack
    delete intMem; // Unexpected Behaviour

    return 0;
}

在您的代码中

std::shared_ptr<int> arr_ptr(arr); // Core dumped

此行等同于我们对上面的新位置所做的操作。问题不在这一行。但是当包含shared_ptr的局部变量超出范围时,会发生在main的末尾。