auto_ptr和原始指针之间的const差异?

use*_*840 3 c++

我意识到,当你这样做时const auto_ptr<X> ptr = variable,你仍然可以修改auto_ptr指向的变量的内容.对于原始指针const X * ptr = variable,const会阻止您修改它.

那么在auto_ptr前面使用const的目的究竟是什么?

R S*_*ahu 8

这个说法:

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.
Run Code Online (Sandbox Code Playgroud)

相当于:

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.
Run Code Online (Sandbox Code Playgroud)

这个说法:

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.
Run Code Online (Sandbox Code Playgroud)

相当于:

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.
Run Code Online (Sandbox Code Playgroud)

这个说法:

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.
Run Code Online (Sandbox Code Playgroud)

相当于:

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.
Run Code Online (Sandbox Code Playgroud)

这个说法:

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.
Run Code Online (Sandbox Code Playgroud)

相当于:

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.
Run Code Online (Sandbox Code Playgroud)