2

I want to guarantee that pointer I passed to function cannot be deleted inside this function (I mean compiler would generate an error on processing such function). The following is the original situation.

void foo(Bar *bar) { delete bar; }

Now I unsuccessfully tried some ways.

void foo(Bar *bar) { delete bar; }
void foo(const Bar * const bar) { delete bar; } { delete bar; }
template <typename T> void foo(const T &t) { delete t; } // calling foo(bar);

I want to know is there some way prohibit deleting pointer And if it isn't possible why it was made?

Loom
  • 9,768
  • 22
  • 60
  • 112

2 Answers2

1

It is not possible. You can try to delete everything. The compiler can not complain, but at runtime you can get undefined behaviour. Look at the following code:

int const i=4;
int const* pi = &i;
delete pi;

which compiles but results in a runtime error. As you can see you can even delete a pointer to a const object located at the stack. The standad allows it (Herb Sutter worte about it, but I don't find a link), because destructors needs to clean up const (RAII) objects when leaving a scope. In any case a function is able to get the address of a parameter and call delete on it. Even if you work with a private destructor and friend functions which are able to destroy these objects you can not prevent these functions from beeing called. I think your only choice is to trust the called function.

Jan Herrmann
  • 2,717
  • 17
  • 21
0

1) If you are declaring the function, you prevent the pointer from being deleted by not deleting it.

2) If you want to convey the function will not delete it, pass the object by reference instead of by pointer: void foo(Bar& bar);

3) If you really want bonus points, use a smart pointer class instead of raw pointers (e.g. shared_ptr, unique_ptr, etc.)

Corollary to 3) If you don't want anyone else deleting the object (i.e. you want a factory object to do the memory management), create the destructor as private and then any functions that call delete on the object would cause a compiler error.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42