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

c++ - How to pass std::unique_ptr around?

I am having my first attempt at using C++11 unique_ptr; I am replacing a polymorphic raw pointer inside a project of mine, which is owned by one class, but passed around quite frequently.

I used to have functions like:

bool func(BaseClass* ptr, int other_arg) {
  bool val;
  // plain ordinary function that does something...
  return val;
}

But I soon realized that I wouldn't be able to switch to:

bool func(std::unique_ptr<BaseClass> ptr, int other_arg);

Because the caller would have to handle the pointer ownership to the function, what I don't want to. So, what is the best solution to my problem?

I though of passing the pointer as reference, like this:

bool func(const std::unique_ptr<BaseClass>& ptr, int other_arg);

But I feel very uncomfortable in doing so, firstly because it seems non instinctive to pass something already typed as _ptr as reference, what would be a reference of a reference. Secondly because the function signature gets even bigger. Thirdly, because in the generated code, it would be necessary two consecutive pointer indirections to reach my variable.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you want the function to use the pointee, pass a reference to it. There's no reason to tie the function to work only with some kind of smart pointer:

bool func(BaseClass& base, int other_arg);

And at the call site use operator*:

func(*some_unique_ptr, 42);

Alternatively, if the base argument is allowed to be null, keep the signature as is, and use the get() member function:

bool func(BaseClass* base, int other_arg);
func(some_unique_ptr.get(), 42);

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

1.4m articles

1.4m replys

5 comments

57.0k users

...