non destructable pointer
Hi
In our current system we have a need to hand out pointers, either as
interface pointers or arrays of pointers (we cannot directly hold
references in an STL container). Some of the pointers will be pointing
to statically allocated (not on the heap) objects, meaning a
Boost.SharedPointer or just a simple "delete" is a no-go!
To indicate that we are planning to introduce a NonDeletePtr<> that
will prevent deletion and indicate that memory handling is not an issue
for the recieving part.
My Qustion is: Is the following a good idea?
Assume we have the following class A:
class A
{
public:
int a;
};
(tough one :-)
And a template class NonDeletePtr<> that signals that the pointer is
not to be deleted (We could call it NotToDeletePtr<> instead). We then
have the class B that contains an A and can hand it out using a method
getA, like:
class B
{
public:
NonDeletePtr<A> getA()
{
return &a;
}
private:
A a;
};
The code that uses these classes can look like:
int main(int argc, char* argv[])
{
A a;
B b;
{ // handing out B::a
NonDeletePtr<A> aPtr = b.getA();
aPtr->a = 42;
delete aPtr; // not legal - compile error
delete *aPtr; // not legal - compile error
}
{ // an A can be used as normal
A* pa = new A;
delete pa;
}
}
The template class can look like:
template <class PTR>
class NonDeletePtr
{
public:
NonDeletePtr():ptr(0){}
NonDeletePtr(PTR & ptr)
{
NonDeletePtr::ptr = ptr;
}
NonDeletePtr(PTR * ptr)
{
NonDeletePtr::ptr = ptr;
}
// copy constructor
PTR* operator ->(){return ptr;}
PTR& operator*(){return *ptr;}
private:
PTR* ptr;
};
Best Regards,
Kristian Lippert
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]