简体   繁体   中英

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 )

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[] . You will need to use 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:

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.

Or shared_ptr<std::basic_string<unsigned char>> if you need dynamically selected size.

With modern C++, there isn't a good reason to use new, delete or naked arrays. If you need them for compatibility, there is always .data().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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