gpt4 book ai didi

c++ - auto_ptr 和原始指针之间的 const 区别?

转载 作者:太空狗 更新时间:2023-10-29 20:02:39 24 4
gpt4 key购买 nike

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

那么在 auto_ptr 前面加上 const 的目的到底是什么?

最佳答案

这个声明:

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.

关于c++ - auto_ptr 和原始指针之间的 const 区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37932574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com