STD :: shared_ptr operator [] equivalent access

In C ++ 17, std::shared_ptr has an operator [] to enable indexing of vector pointers ( http://en.cppreference.com/w/cpp/memory/shared_ptr/operator_at )

How to get similar access if such an 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]; 
+5
source share
1 answer

Like this:

 data.get()[3] 

However, remember what Nathan said in the comments. The default deliter std::shared_ptr<unsigned char> invalid for the pointer highlighted by new[] . You will need to use std::shared_ptr::reset(Y* ptr, Deleter d); with appropriate debiter:

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

Or, if you don't like the ugliness of lambda, you can define a reuse helper:

 struct array_deleter { template<typename T> void operator()(const T* p) { delete[] p; } }; // ... data.reset(new unsigned char[10], array_deleter()); 
+9
source

Source: https://habr.com/ru/post/1261273/


All Articles