简体   繁体   English

std :: shared_ptr operator []等效访问

[英]std::shared_ptr operator [] equivalent access

In C++17 std::shared_ptr has an operator [] to allow indexing vector-based pointers ( http://en.cppreference.com/w/cpp/memory/shared_ptr/operator_at ) 在C ++ 17中, std::shared_ptr有一个operator []来允许索引基于向量的指针( http://en.cppreference.com/w/cpp/memory/shared_ptr/operator_at

How do I obtain similar accessing if such operator is not available and I still want to use a smart pointer for an array of elements such as: 如果这样的操作符不可用,我如何获得类似的访问,我仍然想要使用智能指针来获取元素数组,例如:

std::shared_ptr<unsigned char> data;
data.reset(new unsigned char[10]>;
// use data[3];

Like this: 像这样:

data.get()[3]

However, keep in mind what Nathan said in comments. 但是,请记住内森在评论中所说的话。 The default deleter of std::shared_ptr<unsigned char> is wrong for a pointer allocated by new[] . 对于由new[]分配的指针, std::shared_ptr<unsigned char>的缺省删除器是错误的。 You will need to use std::shared_ptr::reset(Y* ptr, Deleter d); 你需要使用std::shared_ptr::reset(Y* ptr, Deleter d); with an appropriate deleter: 用适当的删除器:

data.reset(new unsigned char[10], [](auto p){ delete[] p; });

Or, if you don't like the ugliness of the lambda, you can define a reusable helper: 或者,如果你不喜欢lambda的丑陋,你可以定义一个可重用的帮助器:

struct array_deleter {
    template<typename T> void operator()(const T* p) { 
        delete[] p; 
    }
};

// ...

data.reset(new unsigned char[10], array_deleter());

Use shared_ptr<std::array<unsigned char, 10>> instead. 请改用shared_ptr<std::array<unsigned char, 10>>

Or shared_ptr<std::basic_string<unsigned char>> if you need dynamically selected size. 或者shared_ptr<std::basic_string<unsigned char>>如果需要动态选择的大小。

With modern C++, there isn't a good reason to use new, delete or naked arrays. 使用现代C ++,没有充分的理由使用new,delete或naked数组。 If you need them for compatibility, there is always .data(). 如果你需要兼容性,总会有.data()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM