Sometimes I need a reference counting smart pointer that should not be nullptr. For example, I want to share a very heavy object without copying. And it's more convenient to place it on the heap. So I could use a shared_ptr. Also, I don't need to assign nullptr to this pointer or reassign it. So I don't want to check for nullptr in code that uses it. I think it would be useful to have a pointer that cannot be nullptr and cannot be reassigned.
I wrote a small prototype that has this features.
#include <iostream>
#include <string>
#include <memory>
#include <exception>
#include <thread>
using namespace std;
// Box cannot hold nullptr
template<class T>
class Box
{
public:
template <class... Args>
static Box<T> create(Args&&... args)
{
return Box<T>(make_shared<T>(std::forward<Args>(args)...));
}
T * operator-> () const
{
return ptr.operator -> ();
}
private:
Box(const shared_ptr<T> & ptr)
: ptr(ptr)
{}
shared_ptr<T> ptr;
};
struct Test
{
Test(int i, double d, const string & s)
: i(i), d(d), s(s)
{
cout << "Test ctor" << endl;
}
~Test()
{
cout << "Test dtor" << endl;
}
Test(const Test & test) = delete;
Test(Test && test) = delete;
Test & operator = (const Test & test) = delete;
Test & operator = (Test && test) = delete;
int i;
double d;
string s;
};
void print(const Box<Test> & test)
{
// there is no need to check for nullptr
cout << test->i << " " << test->d << " " << test->s << endl;
}
void twice(Box<Test> test)
{
// there is no need to check for nullptr
test->i *= 2;
test->d *= 2;
test->s += test->s;
}
/*
stdout:
Test ctor
42 3.14 hello
84 6.28 hellohello
Test dtor
*/
int main()
{
Box<Test> test = Box<Test>::create(42, 3.14, "hello");
print(test);
thread t(twice, test);
t.join();
print(test);
}
Is this code correct? And is this a good approach?
Update: It looks like I found a ready solution https://github.com/dropbox/nn
Related discussions:
1) https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/5TPClBA1fs8
2) http://boost.2283326.n4.nabble.com/Why-no-non-null-smart-pointers-td2642959.html
3) https://lists.boost.org/Archives/boost/2013/10/206732.php
nullptr
sounds like the very definition of a reference. Why not just use references? \$\endgroup\$ptr.operator -> ()
overptr->get()
? \$\endgroup\$