|
-
February 4th, 2017, 09:23 AM
#1
Returning a (NULL) boost_shared_ptr
I'm building a program which defines this function:-
Code:
boost::shared_ptr<SysEx>
MidiRegionView::find_canvas_sys_ex (MidiModel::SysExPtr s)
{
// Some stuff to return a valid object
// Or if that's not possible...
return NULL;
}
Presumably some compilers accept the above and return a boost::shared_ptr<SysEx> that's equivalent to a NULL pointer. However, MSVC tells me that it can't convert an int to boost::shared_ptr<SysEx>. I changed the return value to look like this:-
Code:
boost::shared_ptr<SysEx>
MidiRegionView::find_canvas_sys_ex (MidiModel::SysExPtr s)
{
// Some stuff to return a valid object
// Or if that's not possible...
return boost::shared_ptr<SysEx>();
}
The compiler seems happy now - but is that the right way to return something that's equivalent to a NULL pointer?
"A problem well stated is a problem half solved.” - Charles F. Kettering
-
February 7th, 2017, 08:16 AM
#2
Re: Returning a (NULL) boost_shared_ptr
boost::shared_ptr<SysEx>() will work, but it's simpler to just return nullptr.
NULL is an old macro for integer 0, which should be avoided in modern C++.
By the way, shared_ptr is included in the C++ standard, so you shouldn't normally need to use boost for smart pointers.
-
February 7th, 2017, 09:01 AM
#3
Re: Returning a (NULL) boost_shared_ptr
I had a quick glance at the boost documentation. There doesn't appear to be any implicit constructor that NULL (integer) can bind to, so it appears that MSVC is correct and the other compilers are wrong.
nullptr can only bind to pointer types, in this case the implicit constructor "shared_ptr(std::nullptr_t);"
Instead of "return nullptr;", you can also write "return {};".
-
February 16th, 2017, 09:00 AM
#4
Re: Returning a (NULL) boost_shared_ptr
The last Visual Studio versions support std::shared_ptr, which is C++11 standard compliant.
So, if you have at least Visual Studio 2010, is easier and better to use std::shared_ptr instead of boost::shared_ptr.
Here is a simple example:
Code:
// ...
#include <memory>
#include <iostream>
class CFoo
{
// ...
};
std::shared_ptr<CFoo> TestFunction(int nTest)
{
std::shared_ptr<CFoo> spResult;
if (nTest > 100)
{
spResult = std::make_shared<CFoo>();
}
return spResult;
}
int main()
{
auto spResult = TestFunction(100); // spResult contains a null pointer
if (spResult)
std::cout << "First try: spResult contains a valid pointer" << std::endl;
spResult = TestFunction(101); // spResult contains a valid CFoo pointer
if(spResult)
std::cout << "Second try: spResult contains a valid pointer" << std::endl;
return 0;
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|