C++智能指针作为成员变量

 
  1. class Device {

  2. };

  3.  
  4. class Settings {

  5. Device *device;

  6. public:

  7. Settings(Device *device) {

  8. this->device = device;

  9. }

  10.  
  11. Device *getDevice() {

  12. return device;

  13. }

  14. };

  15.  
  16. int main() {

  17. Device *device = new Device();

  18. Settings settings(device);

  19. // ...

  20. Device *myDevice = settings.getDevice();

  21. // do something with myDevice...

  22. }

  23. 复制代码

  • C++11为我们提供了shared_ptr、unique_ptr和weak_ptr这三种智能指针帮助我们更方便安全的使用动态内存。它们都定义在memory头文件中。智能指针的常见用法大家都应该很熟悉了,今天我想说一下智能指针作为成员变量时的用法。比如上面这段代码,我想类Settings中的Device指针换成智能指针,那么getDevice应该是什么样的呢?

  • 这里主要的决定因素是你Device对象的所有权策略,即你想要谁去拥有它,决定它的生命期。如果只有Settings对象拥有它,当Settings析构的时候你希望Device也自动被析构。那么你需要用unique_ptr,此时Settings独自拥有Device对象的,因此Device的析构就只有Settings负责。在这种情况下,getDevice可以返回一个引用。

 
  1. #include <memory>

  2.  
  3. class Device {

  4. };

  5.  
  6. class Settings {

  7. std::unique_ptr<Device> device;

  8. public:

  9. Settings(std::unique_ptr<Device> d) {

  10. device = std::move(d);

  11. }

  12.  
  13. Device& getDevice() {

  14. return *device;

  15. }

  16. };

  17.  
  18. int main() {

  19. std::unique_ptr<Device> device(new Device());

  20. Settings settings(std::move(device));

  21. // ...

  22. Device& myDevice = settings.getDevice();

  23. // do something with myDevice...

  24. }

  25. 复制代码

  • 如果你希望Device对象不只是Settings所独有,那么就需要使用shared_ptr了。这样直到所有拥有Device的对象都析构了之后,Device才会析构。
 
  1. #include <memory>

  2.  
  3. class Device {

  4. };

  5.  
  6. class Settings {

  7. std::shared_ptr<Device> device;

  8. public:

  9. Settings(std::shared_ptr<Device> const& d) {

  10. device = d;

  11. }

  12.  
  13. std::shared_ptr<Device> getDevice() {

  14. return device;

  15. }

  16. };

  17.  
  18. int main() {

  19. std::shared_ptr<Device> device = std::make_shared<Device>();

  20. Settings settings(device);

  21. // ...

  22. std::shared_ptr<Device> myDevice = settings.getDevice();

  23. // do something with myDevice...

  24. }

  25.  
发布了78 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43778179/article/details/104971684