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

c++ - Check for null in std::shared_ptr

I was wondering if i need to check whether sp is null before i use it. Correct me if I am wrong but creating an alias will not increase the ref counter and therefore by entering into the method we are working with a shared pointer which we don't know if the embedded pointer has been reset before.. am I correct by assuming this?

Class::MyFunction(std::shared_ptr<foo> &sp)
{    
    ...  
    sp->do_something();  
    ...  
}
question from:https://stackoverflow.com/questions/22220512/check-for-null-in-stdshared-ptr

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

1 Reply

0 votes
by (71.8m points)

Most shared pointers are exactly like normal pointers in this respect. You have to check for null. Depending on the function, you may want to switch to using

void myFunction( Foo const& foo );

, and calling it by dereferencing the pointer (which pushes the responsibility for ensuring that the pointer is not null to the caller).

Also, it's probably bad practice to make the function take a shared pointer unless there are some special ownership semantics involved. If the function is just going to use the pointer for the duration of the function, neither changing it or taking ownership, a raw pointer is probably more appropriate, since it imposes less constraints on the caller. (But this really depends a lot on what the function does, and why you are using shared pointers. And of course, the fact that you've passed a non-const reference to the shared pointer supposes that you are going to modify it, so passing a shared pointer might be appropriate.)

Finally, different implementations of shared pointers make it more or less difficult to check for null. With C++11, you can use std::shared_ptr, and just compare it to nullptr naturally, as you'd expect. The Boost implementation is a bit broken in this respect, however; you cannot just compare it to 0 or NULL. You must either construct an empty boost::shared_ptr for the comparison, or call get on it and compare the resulting raw pointer to 0 or NULL.


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

...