Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c++ - C++11 Smart Pointer Policies

As I understand it, in the current specification of C++11, one should use:

  • std::unique_ptr<> for one owner (most of the time)
  • std::shared_ptr<> only when there are multiple owners in acyclic structure
  • std::weak_ptr<> sparingly only when there are cycles that need to be broken
  • A raw pointer as a handle to memory (no ownership) when a reference would not suffice

So my questions are:

  1. Are these policies sufficient or are there additional policies that I should be aware of?
  2. Are scoped_ptr<> and auto_ptr<> effectively obsolete?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Are scoped_ptr<> and auto_ptr<> effectively obsolete?

auto_ptr is deprecated in C++11, so there's your answer. scoped_ptr doesn't exist in C++11 and never did. The main reason to use boost::scoped_ptr is to ensure that ownership is never transferred (unless you cheat, of course). Then again, if you use unique_ptr, ownership can only be transferred if you use std::move or similar constructs. Or, as Howard points out, just make it a const std::unique_ptr.

So it's really up to you whether you want that extra bit of insurance. Also boost::scoped_ptr doesn't have deleter support. So unique_ptr can play tricks that boost::scoped_ptr cannot.

std::weak_ptr<> sparingly only when there are cycles that need to be broken

I can't say I agree with this policy necessarily. A weak_ptr should be used when an object may want to talk to something else, but it doesn't own that something else. Which means that it can be deleted at any time, and the holder of the weak_ptr needs to be able to handle that deletion anytime it tries to talk to it.

Breaking cycles is one of the uses of weak_ptr; it should not be the only time it is used.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...