Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 image 823
rph Avatar asked Dec 14 '16 14:12

rph


People also ask

Can shared_ptr be Nullptr?

A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .

What is a shared_ptr in C++?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.

When should you use shared_ptr?

So, we should use shared_ptr when we want to assign one raw pointer to multiple owners. // referring to the same managed object. When to use shared_ptr? Use shared_ptr if you want to share ownership of a resource.

Can shared_ptr be copied?

The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr . Constructing a new shared_ptr using the raw underlying pointer owned by another shared_ptr leads to undefined behavior.


1 Answers

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());
like image 54
eerorika Avatar answered Oct 27 '22 23:10

eerorika