2016-06-20 2 views
2

Я понял, что когда вы делаете const auto_ptr<X> ptr = variable, вы по-прежнему можете изменять содержимое переменной, на которую указывают точки auto_ptr. Для необработанного указателя const X * ptr = variable, const запретит вам его изменять.Разница констант между auto_ptr и необработанным указателем?

Так что же такое цель иметь const перед auto_ptr?

+1

Не отвечая на вопрос. Просто комментируем. Вы действительно должны использовать 'std :: unique_ptr' и/или' std :: shared_ptr', а не устаревшие (по уважительной причине) 'std :: auto_ptr'. Просто скажите нет ... –

+0

«Точка» заключается в том, что язык не имеет специальных правил для вещей, независимо от того, являются ли они семантически полезными. 'const' может быть применен к * любому типу *; программист должен решить, оправдан ли он для конкретного обстоятельства. –

ответ

6

Это утверждение:

auto_ptr<X> ptr = variable; 
// non-const auto_ptr object pointing to a non-const X object 
// Can change the contents of the X object being pointed at. 
// Can change where the auto_ptr itself points at. 

равносильна этому:

X* ptr = variable; 
// non-const pointer to a non-const X object 
// Can change the contents of the X object being pointed at. 
// Can change where the pointer itself points at. 

Это утверждение:

const auto_ptr<X> ptr = variable; 
// const auto_ptr object pointing to a non-const X object 
// Can change the contents of the X object being pointed at. 
// Can't change where the auto_ptr itself points at. 

равносильна этому:

X* const ptr = variable; 
// const pointer to a non-const X object 
// Can change the contents of the X object being pointed at. 
// Can't change where the pointer itself points at. 

Это утверждение:

auto_ptr<const X> ptr = variable; 
// non-const auto_ptr object pointing to a const X object 
// Can't change the contents of the X object being pointed at. 
// Can change where the auto_ptr itself points at. 

равносильна этому:

const X * ptr = variable; 
// non-const pointer to a const X object 
// Can't change the contents of the X object being pointed at. 
// Can change where the pointer itself points at. 

Это утверждение:

const auto_ptr<const X> ptr = variable; 
// const auto_ptr object pointing to a const X object 
// Can't change the contents of the X object being pointed at. 
// Can't change where the auto_ptr itself points at. 

равносильна этому:

const X* const ptr = variable; 
// const pointer to a const X object 
// Can't change the contents of the X object being pointed at. 
// Can't change where the pointer itself points at. 
+0

спасибо, не могли бы вы рассказать мне другой эквивалент? Или где я могу найти эти эквиваленты и объяснения? – user1701840

+0

@ user1701840, надеюсь, что обновленные ответы будут адресованы. –

+0

Спасибо за изменения, @RemyLebeau. –

Смежные вопросы