Code: Select all
// (c) 2014 Nic Anderson (chronologicaldot)
// zlib license
namespace util {
template<class T>
struct sp
{
T* p;
sp()
{}
sp( T& item )
: p( &item )
{}
sp( T* pointer )
: p( pointer )
{}
void set( T& item )
{
p = &item;
}
void set( T* pointer )
{
p = pointer;
}
T& operator = ( T& item )
{
p = &item;
return *p;
}
T& operator = ( T* pointer )
{
p = pointer;
return *p;
}
operator T& ()
{
return *p;
}
inline T& o() // object
{
return *p;
}
T& operator * ()
{
return *p;
}
T copy()
{
return (T)*p;
}
};
}
Code: Select all
class TestClass {
public:
int i;
TestClass()
{ i = 0; }
int func()
{ return i; }
bool like( TestClass other )
{ return i == other.i; }
};
sp<TestClass> p1;
TestClass test;
p1 = test;
// Direct initialization is allowed
sp<TestClass> p2 = new TestClass();
// Object referencing is easy to type
p2.o().i = 1;
// casting!!!!
if ( p1.o().like( p2 ) )
{ ... }
// The pointer is still accessible!
p1.p = p2.p;
What I used to do:
Code: Select all
// assume this: TestClass* p = new TestClass();
(*p).func();
// or
p->func();
But anyways...