将 C 数组名称视为原始指针并复制到 shared_ptr
Treat C array name as raw pointer and copy to 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/
谢谢基思:^)
arr
是在栈上静态分配的,而不是用 new
动态分配的。一旦共享指针退出作用域,它将尝试对该指针调用 delete
。由于指针引用的内存未分配 new
,因此结果未定义。
std::shared_ptr<>
用于所有意图和目的,用于管理内存的所有权,否则手动操作会很乏味。在这种情况下,编译器会使用堆栈帧自动管理内存。
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
这一行等同于我们对上面的 placement new 所做的。问题不在这一行。但是当包含 shared_ptr
的局部变量超出范围时发生在 main 的末尾。
鉴于数组名称被隐式转换为指针,我如何将所述数组的位置复制到 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/
谢谢基思:^)
arr
是在栈上静态分配的,而不是用 new
动态分配的。一旦共享指针退出作用域,它将尝试对该指针调用 delete
。由于指针引用的内存未分配 new
,因此结果未定义。
std::shared_ptr<>
用于所有意图和目的,用于管理内存的所有权,否则手动操作会很乏味。在这种情况下,编译器会使用堆栈帧自动管理内存。
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
这一行等同于我们对上面的 placement new 所做的。问题不在这一行。但是当包含 shared_ptr
的局部变量超出范围时发生在 main 的末尾。