乐闻世界logo
搜索文章和话题

Difference between `const shared_ptr< T >` and ` shared_ptr <const T>`?

1 个月前提问
1 个月前修改
浏览次数18

1个答案

1

const shared_ptr vs shared_ptr

const shared_ptrshared_ptr 两者看似类似,但实际上在用途和含义上有重要区别。

1. const shared_ptr

当我们说 const shared_ptr<T> 时,这意味着智能指针本身是常量。也就是说,这个智能指针不能被改变指向其他对象,但是通过它指向的对象是可以被修改的(如果对象类型T允许的话)。

例子

cpp
#include <memory> struct Example { int value; }; int main() { auto example = std::make_shared<Example>(); example->value = 10; // 正常操作 const std::shared_ptr<Example> constPtr = example; constPtr->value = 20; // 这是允许的,因为Example的value是可以修改的 // constPtr = std::make_shared<Example>(); // 错误!constPtr是const,不能改变它指向的对象 }

2. shared_ptr

shared_ptr<const T> 表示通过这个智能指针,你不能修改它所指向的对象,即对象是常量。但是,你可以改变智能指针本身,让它指向另一个对象。

例子

cpp
#include <memory> struct Example { int value; }; int main() { auto example = std::make_shared<Example>(); example->value = 10; // 正常操作 std::shared_ptr<const Example> constElemPtr = example; // constElemPtr->value = 20; // 错误!constElemPtr指向的是const Example,不能修改value constElemPtr = std::make_shared<Example>(); // 正常操作,可以改变指向 }

总结

  • const shared_ptr:智能指针本身是常量,不能改变其指向,但可以修改通过它访问的对象(如果对象类型T允许的话)。
  • shared_ptr:通过智能指针访问的对象是常量,不能被修改,但智能指针本身可以改变其指向。

这种区别在使用时非常重要,因为它直接影响到你的对象和智能指针的行为和安全性。在设计接口和数据访问时,正确选择这两者之一可以帮助确保代码的健壳性和正确性。

2024年8月2日 16:32 回复

你的答案