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
86 views
in Technique[技术] by (71.8m points)

c++ - Recommended usage of std::unique_ptr


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

1 Reply

0 votes
by (71.8m points)

In theory, you should use unique_ptr for all pointers unless you know you want to share it, in which case you should use shared_ptr. The reason is that unique_ptr has less overhead since it doesn't count references.

However, a unique_ptr is movable but not copyable, so using one as a member variable can require you to write more code (eg a move constructor), passing one by value means you'll need to use std::move and so on. As a result some people use shared_ptr out of laziness, because it's just easier, and the perf difference may not be significant for their app.

Finally a raw pointer is fine for observation - pointer uses that can never affect lifetime. Careful choice of the right pointer type can give those who read your code a good understanding of what you are doing. For more, see Herb Sutter's essay, Elements of C++ Style, specifically the "no delete" section.


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

...