tags:

views:

102

answers:

6

Hi, I'm relatively new to C++ and OOP in general and currently trying to make such a class that allows to dereference and delete a dead or invalid pointer without any care of having undefined behavior or program fault in result, and I want to ask you is it a good idea and is there something similar which is already implemented by someone else? or maybe I'm doing something completely wrong?

I've just started making it and here is the code I currently have:

template<class T> class SafeDeref
{
 public:

  T& operator *()
  {
   hash_set<T*>::iterator it = theStore.find(reinterpret_cast<T*>(ptr));

   if (it != theStore.end())
    return *this;
   return theDefaultObject;
  }

  T* operator ->()
  {
   hash_set<T*>::iterator it = theStore.find(reinterpret_cast<T*>(ptr));

   if (it != theStore.end())
    return this;
   return &theDefaultObject;
  }

  void* operator new(size_t size)
  {
   void* ptr = malloc(size * sizeof(T));

   if (ptr != 0)
    theStore.insert(reinterpret_cast<T*>(ptr));
   return ptr;
  }

  void operator delete(void* ptr)
  {
   hash_set<T*>::iterator it = theStore.find(reinterpret_cast<T*>(ptr));

   if (it != theStore.end()) {
    theStore.erase(it);
    free(ptr);
   }
  }

 protected:

  static bool isInStore(T* ptr)
  {
   return theStore.find(ptr) != theStore.end();
  }

 private:

  static T theDefaultObject;

  static hash_set<T*> theStore;
};

The idea is that each class with the safe dereference should be inherited from it like this:

class Foo
 : public SafeDeref<Foo>
{
 void doSomething();
};

So... Any advices?

Thanks in advance.

P.S. If you're wondering why I need this... well, I'm creating a set of native functions for some scripting environment, and all of them use pointers to internally allocated objects as handles to them and they're able to delete them as well (input data can be wrong), so this is kinda protection from damaging host application's memory

And I really sorry for my bad English

Edit: unfortunately shared_ptr and similar aren't for me... The scripting language itself (its name is Pawn by the way) is very limited and every thing there is made of 32-bit cells, and I should place in such a cell a pointer to the object. In general the man who writes a script doesn't even know of that, so when he pass an invalid value it should be detected some way and it should not do anything in that case.

Edit2: I'm feeling like I misunderstood something about shared_ptr... I will take a look at them, thank you for all your replies!

Edit3: Hmm, what I'm trying to make isn't actually for me and preventing me from stupid code or whatever, it is aimed to guard the application (which is a game server I'm writing a plugin for (they share the same address space), to extend its scripting features) from bad scripts which can cause the server to crash, I'm sorry that I didn't tell this earlier and nobody understood what I mean... Thanks for replies anyway.

+1  A: 

Take a look at std::auto_ptr. Better yet, take a look at boost::shared_ptr.

wilhelmtell
`auto_ptr` is deprecated by `unique_ptr` (when available...) otherwise `boost::scoped_ptr` is safer (though it does not cover all use cases)
Matthieu M.
@Matthieu `auto_ptr` isn't deprecated. Where did you hear that?
wilhelmtell
It is deprecated in the new C++0x norm and is not advised to be used when you can use unique_ptr or shared_ptr/scoped_ptr etc...
Nikko
@Nikko There is no C++0x, and there won't be (one implemented) for years to come. Yes, `boost::shared_ptr` is better, and I said it in my answer. But `std::auto_ptr` isn't deprecated. I too would like it to be deprecated in favor of `boost::shared_ptr`, but it isn't.
wilhelmtell
C++0x is the new norm for C++, it is starting to be implemented in the last version of main stream compilers ( gcc, visual ). And auto_ptr is deprecated in C++0x in favor of unique_ptr (see §D10 of the final draft proposal). You can check: http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2010/n3092.pdf
Nikko
@Nikko you're saying groundless things here. What do you mean "C++0x is the new norm for C++"? New norm for whom? How can it be a new norm if it's not even the current standard? Not even implemented by any compiler! Where are you taking these claims from? Right now there is a C++ standard, and it's called C++03. That standard includes the `std::auto_ptr` class in the STL. That's it, there are no small letters or footnotes here.
wilhelmtell
I meant "standard", sorry
Nikko
+1  A: 

I think you should take a look at STL Automatic Pointer

template <class X> class auto_ptr;

This class provides a limited "garbage collection" facility for pointers, by allowing pointers to have the elements they point to automatically destroyed when the auto_ptr object is itself destroyed.

Example:

//Safe code, with auto_ptr
void f()
{
  auto_ptr<T> pt( new T );

  /*...more code...*/

} // pt's destructor is called as it goes out of scope, and the object is deleted automatically

See more about it here.

Be aware of the screwed copy semantics of `auto_ptr` though, it's easy to call undefined behavior on you when using this beast.
Matthieu M.
A: 

Just use std::/boost:: shared_ptr.

DeadMG
A: 

I agree with what people are saying that you're better off using shared pointers most all of the time. But there are some particular cases where "strong"/"weak" pointer distinctions are useful. Make sure you've got one of those cases!

If so, then you may be interested either using or copying the interface of QWeakPointer and QSharedPointer in Qt:

http://doc.trolltech.com/4.6-snapshot/qsharedpointer.html#details

http://doc.trolltech.com/4.6-snapshot/qweakpointer.html#details

Be aware that there are issues to be considered in multithreaded environments with this kind of design. If one thread is able to release objects while another is running, then between the time you say "Oh, the address is okay..." and when the caller tries to use the address, it could go bad. This is why Qt makes you promote a weak pointer to a shared pointer before dereferencing it!

(Note: std::auto_ptr has been "deprecated" because it treats assignment as a transfer of ownership, and that breaks the expectations of generic algorithms which assume that "A = B;" will semantically copy B to A... not put B's contents into A and then erase B. This is addressed somewhat in std::unique_ptr, but I wrote a post about the fuzzy state of smart pointer support in current compilers.)

Hostile Fork
`shared_ptr` has a weak ownership smart pointer as well (`weak_ptr`)
James McNellis
I hadn't noticed it. But I feel like the story's never really straight on issues like thread safety or other things with these TR1-and-beyond extensions. The documentation is spread out and they never seem to work right...much easier to see what's what in the Qt classes: http://hostilefork.com/2009/07/10/smart-pointer-casting-study/
Hostile Fork
+1  A: 

Ah, undefined behavior... so much isn't it ?

Well, the first issue you are going to face is that it's incredibly difficult to fend off undefined behavior with a library. Your use of a DefaultObject is not new, however it means that each class should be able to provide such an object.

Furthermore, look at your implementation: your are obviously using CRTP here, to know about the most derived type so as to correctly cast the pointer, however CRTP is annoying when going on multiple levels:

template <class D>
class Base: public SafeDeref<D>
{
};

class Derived: public Base<Derived> {};

Notice the issue ? Base is template, which is annoying because of the constraint it puts on the implementation of its methods.

I would recommend using a simple but proven technic: RAII. Instead of trying to delete the pointer by yourself, let go of its ownership to an object which will manage it and ensure it's available as long as you need it... then discard it.

The traditional way is the std::auto_ptr, however it's deprecated in C++0x in favor of the std::unique_ptr.

Otherwise, if you want several objects sharing the ownership, so that the resource is only freed when the last of them dies, then take a look at boost::shared_ptr and its accomplice boost::weak_ptr.

Finally, if you want containers of objects that are dynamically allocated, and you want the container to have ownership, instead of using STL containers with smart pointers, directly use the Boost.PointerContainer library, for example: boost::ptr_vector. It's faster and the syntax is geared toward pointers so it's easier to manipulate them :)

Matthieu M.
+1  A: 

You are probably writing this mechanism in order to make your code more robust. For example, to avoid the kinds of problems you encounter when you do something like this:

int main()
{
  Obj* myobj = new Obj;
  // magic happens
  delete myobj;  // note we do not set myobj to NULL
  // more majic happens
  if( myobj )
  {
    myobj->foo();  // OOPS: pointer is wild - UB, probably segfault
    delete myobj;  // OOPS: pointer already deleted - UB
  }
  return 0;
}

So you write a class that wraps up the pointer and makes it impossible to dereference or delete a wild pointer.

This is a very bad idea. You are not making your code more robust, or better in any way by doing this. All you are doing is obfuscating your code, making it more complex and possibly less efficient. Moreover you didn't fix the problem you were trying to fix in the first place. Namely, the problem is not that calling through or deleting wild pointers results in a crash, but that you are calling through or deleting those wild pointers to begin with.

So the problem you are having is not caused by the inherent nature of pointers themselves. The problem is your code is, sorry to say, shoddy.

Classes like std::auto_ptr do exist to make managing your dynamically-allocated resources easier, more robust and safer in the face of exceptions. But they do not exist to make poorly-written code somehow magically better. If you write poor code, you will have problems. Even if you use std::auto_ptr or it's ilk.

John Dibling
Yes, something like this
Zeex
@serejko: Sorry, I had submitted accidentally before I was done typing. Please look again.
John Dibling