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];
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 .
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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With