Why doesn't std :: unique_ptr have a const get method?

I understand that it std::unique_ptris as it is and probably will not be changed to cancel backward compatibility, but I was wondering if anyone has a good reason why the spec authors did not overload the method getwith the const option, which looks like

const T* get() const;

follow the intention to unique_ptrbe const.

My best guess is that it is trying to flip pointers and act like T* constinstead of a regular class. As a follow-up question, if I wanted to keep a pointer in a const-like module in a const instance of my class, should I use something other than std::unique_ptrto store data?

Update

In my case, I want to protect myself from misusing the pointer in the class itself. I wrote a const move constructor MyClass(const MyClass&& other)and copied the data from the new instance to another through std::copy. It took a long time to track down the error, because I assumed that the copy should be correct due to real-time protection. I am trying to figure out what I could do to protect myself from this outside of providing a const getter and using it in the class when executing the copy.

+7
source share
4 answers

. , const, , , . . , std::unique_ptr::get - const, const.

, const.

MyClass *pointerToObject
std::unique_ptr<MyClass> smartPointerToObject;

// but you can have also a case
const MyClass *pointerToConstObject
std::unique_ptr<const MyClass> smartPointerToConstObject;

std::unique_ptr::get , .


:

:

InnerClass& GetField() { return *uniquePtrToInnerClass; }
const InnerClass& GetField() const { return *uniquePtrToInnerClass; }

, const- const.

+3

unique_ptr. unique_ptr , , up.get() const T* , ( nullptr, *(up.get()) a const T&).

, , , unique_ptr.

unique_ptr (in/out, const/non-const ..):

+5

a T*const T&, a T const&.

.

get is const, unique_ptr.

.

, , unique_ptr .

std::experimental::propogate_const , , const.

, - , .

, , const , , . .

, T*const const T const& ( T const*).

+5

, , 2 ,

e.g.
    const T* get() const;
    T* get();
    enter code here

, "T * get() const" .

uniq ptr , , - - OWNED (const) [, - - , - ptr].

Perhaps the best option would be std to provide a different version of Uniq ptr that supports the above idiom (only another option would be to get a new class from uniq ptr and provide 2 versions for dereferencing)

0
source

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


All Articles