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

时间:2016-06-20 22:05:16

标签: c++

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

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

1 个答案:

答案 0 :(得分: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.