[英]Using shared_ptr with char*
I can not create:我无法创建:
shared_ptr<char> n_char = make_shared<char>(new char[size_]{});
How can I create我该如何创建
char* chr = new char[size_]{};
using modern pointers?使用现代指针?
shared_ptr n_char = make_shared(new char[size_]{});
shared_ptr n_char = make_shared(new char[size_]{});
make_shared
calls new
inside, so you never use both. make_shared
在里面调用new
,所以你永远不会同时使用两者。 In this case you only call new
, because make_shared
does not work for arrays.在这种情况下,您只调用
new
,因为make_shared
不适用于数组。
However, you still need to make it call the right delete:但是,您仍然需要让它调用正确的删除:
Before C++17 :在 C++17 之前:
You need to specify the deleter explicitly.您需要明确指定删除器。
std::shared_ptr<char> ptr(new char[size_], std::default_delete<char[]>());
Since C++17 :从 C++17 开始:
shared_ptr
gains array support similar to what unique_ptr
already had from the beginning: shared_ptr
获得了类似于unique_ptr
从一开始就已经拥有的数组支持:
std::shared_ptr<char[]> ptr(new char[size_]);
Be aware that done this simple way you are not tracking length and in multi-threaded environment not synchronizing.请注意,以这种简单的方式完成后,您不会跟踪长度并且在多线程环境中不会同步。 If you need the buffer modifiable, making shared pointer to
std::string
, or struct with std::string
and std::mutex
in it, will add a level of indirection, but will be otherwise more convenient to use.如果您需要可修改缓冲区,使共享指针指向
std::string
或其中包含std::string
和std::mutex
的结构,将增加一个间接级别,但使用起来会更方便。
You could use std::default_delete
specialized for arrays您可以使用专门用于数组的
std::default_delete
std::shared_ptr<char> ptr(new char[size_], std::default_delete<char[]>());
See std::default_delete docs .见std::default_delete 文档。 While std::unique_ptr uses default_delete by default when no other deleter is specified and has a partial specialization that handles array types:
虽然 std::unique_ptr 在没有指定其他删除器时默认使用 default_delete 并且具有处理数组类型的部分特化:
std::unique_ptr<char[]> ptr(new char[size_]);
With std::shared_ptr you need to select it manually by passing a deleter to the constructor.使用 std::shared_ptr 您需要通过将删除器传递给构造函数来手动选择它。
Edit: Thanks to Jan Hudec, c++17 includes a partial specialization for array types as well:编辑:感谢 Jan Hudec, c++17 还包括对数组类型的部分特化:
std::shared_ptr<char[]> ptr(new char[size_]); // c++17
对于简单的字符缓冲区:
std::shared_ptr<char> ptr( (char*)operator new( buffer_size_here ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.