How does delete deal with pointer constness? - c++

I was reading this question Deleting a const pointer and wanted to know more about delete behavior. Now, as per my understanding:
delete expression works in two steps:
invoke destructor
then releases the memory (often with a call to free()) by calling operator delete.
operator delete accepts a void*. As part of a test program I overloaded operator delete and found that operator delete doesn't accept const pointer.
Since operator delete does not accept const pointer and delete internally calls operator delete, how does Deleting a const pointer work ?
Does delete uses const_cast internally?

const_cast doesn't really do anything – it's a way to suppress compiler moaning about const-ness of the object. delete keyword is a compiler construct, the compiler knows what to do in this case and doesn't care about const-ness of the pointer.

As this answer says, delete is not a method like any other, but a part of the langage to destruct objects. const-ness has no bearing on destructability.

operator delete accepts a void*. As part of a test program I overloaded operator delete and found that operator delete doesn't accept const pointer.
How did you try this? It certainly does accept const pointers:
#include <memory>
int main() {
void* const px = 0;
delete px;
::operator delete(px);
}
This code is correct, compiles (albeit with a justified warning) and executes.
EDIT: Reading the original article – you aren't talking about a const pointer but a pointer to const, which is something else. The reason why this has to work is described there. As for why it's working: others have said this.

delete is an operator that you can overload. It takes a pointer as an argument, and frees the memory, possibly using free. The compiler allows this whether the pointer is const or not.

delete just makes a call to deallocate the memory the pointer points to, it doesn't change the value of the pointer nor the object. Therefore, delete has nothing to do with the const-ness of the pointer or object pointed to.

Related

Possible memory leak with shared_ptr C++ [duplicate]

Suppose I have the following code:
void* my_alloc (size_t size)
{
return new char [size];
}
void my_free (void* ptr)
{
delete [] ptr;
}
Is this safe? Or must ptr be cast to char* prior to deletion?
Deleting via a void pointer is undefined by the C++ Standard - see section 5.3.5/3:
In the first alternative (delete
object), if the static type of the
operand is different from its dynamic
type, the static type shall be a base
class of the operand’s dynamic type
and the static type shall have a
virtual destructor or the behavior is
undefined. In the second alternative
(delete array) if the dynamic type of
the object to be deleted differs from
its static type, the behavior is
undefined.
And its footnote:
This implies that an object cannot be
deleted using a pointer of type void*
because there are no objects of type
void
.
It depends on "safe." It will usually work because information is stored along with the pointer about the allocation itself, so the deallocator can return it to the right place. In this sense it is "safe" as long as your allocator uses internal boundary tags. (Many do.)
However, as mentioned in other answers, deleting a void pointer will not call destructors, which can be a problem. In that sense, it is not "safe."
There is no good reason to do what you are doing the way you are doing it. If you want to write your own deallocation functions, you can use function templates to generate functions with the correct type. A good reason to do that is to generate pool allocators, which can be extremely efficient for specific types.
As mentioned in other answers, this is undefined behavior in C++. In general it is good to avoid undefined behavior, although the topic itself is complex and filled with conflicting opinions.
It's not a good idea and not something you would do in C++. You are losing your type info for no reason.
Your destructor won't be called on the objects in your array that you are deleting when you call it for non primitive types.
You should instead override new/delete.
Deleting the void* will probably free your memory correctly by chance, but it's wrong because the results are undefined.
If for some reason unknown to me you need to store your pointer in a void* then free it, you should use malloc and free.
Deleting a void pointer is dangerous because destructors will not be called on the value it actually points to. This can result in memory / resource leaks in your application.
If you really must do this, why not cut out the middle man (the new and delete operators) and call the global operator new and operator delete directly? (Of course, if you're trying to instrument the new and delete operators, you actually ought to reimplement operator new and operator delete.)
void* my_alloc (size_t size)
{
return ::operator new(size);
}
void my_free (void* ptr)
{
::operator delete(ptr);
}
Note that unlike malloc(), operator new throws std::bad_alloc on failure (or calls the new_handler if one is registered).
The question makes no sense. Your confusion may be partly due to the sloppy language people often use with delete:
You use delete to destroy an object that was dynamically allocated. Do do so, you form a delete expression with a pointer to that object. You never "delete a pointer". What you really do is "delete an object which is identified by its address".
Now we see why the question makes no sense: A void pointer isn't the "address of an object". It's just an address, without any semantics. It may have come from the address of an actual object, but that information is lost, because it was encoded in the type of the original pointer. The only way to restore an object pointer is to cast the void pointer back to an object pointer (which requires the author to know what the pointer means). void itself is an incomplete type and thus never the type of an object, and a void pointer can never be used to identify an object. (Objects are identified jointly by their type and their address.)
Because char has no special destructor logic. THIS won't work.
class foo
{
~foo() { printf("huzza"); }
}
main()
{
foo * myFoo = new foo();
delete ((void*)foo);
}
The d'ctor won't get called.
A lot of people have already commented saying that no, it's not safe to delete a void pointer. I agree with that, but I also wanted to add that if you're working with void pointers in order to allocate contiguous arrays or something similar, that you can do this with new so that you'll be able to use delete safely (with, ahem, a little of extra work). This is done by allocating a void pointer to the memory region (called an 'arena') and then supplying the pointer to the arena to new. See this section in the C++ FAQ. This is a common approach to implementing memory pools in C++.
If you want to use void*, why don't you use just malloc/free? new/delete is more than just memory managing. Basically, new/delete calls a constructor/destructor and there are more things going on. If you just use built-in types (like char*) and delete them through void*, it would work but still it's not recommended. The bottom line is use malloc/free if you want to use void*. Otherwise, you can use template functions for your convenience.
template<typename T>
T* my_alloc (size_t size)
{
return new T [size];
}
template<typename T>
void my_free (T* ptr)
{
delete [] ptr;
}
int main(void)
{
char* pChar = my_alloc<char>(10);
my_free(pChar);
}
There is hardly a reason to do this.
First of all, if you don't know the type of the data, and all you know is that it's void*, then you really should just be treating that data as a typeless blob of binary data (unsigned char*), and use malloc/free to deal with it. This is required sometimes for things like waveform data and the like, where you need to pass around void* pointers to C apis. That's fine.
If you do know the type of the data (ie it has a ctor/dtor), but for some reason you ended up with a void* pointer (for whatever reason you have) then you really should cast it back to the type you know it to be, and call delete on it.
I have used void*, (aka unknown types) in my framework for while in code reflection and other feats of ambiguity, and so far, I have had no troubles (memory leak, access violations, etc.) from any compilers. Only warnings due to the operation being non-standard.
It perfectly makes sense to delete an unknown (void*). Just make sure the pointer follows these guidelines, or it may stop making sense:
1) The unknown pointer must not point to a type that has a trivial deconstructor, and so when casted as an unknown pointer it should NEVER BE DELETED. Only delete the unknown pointer AFTER casting it back into the ORIGINAL type.
2) Is the instance being referenced as an unknown pointer in stack bound or heap bound memory? If the unknown pointer references an instance on the stack, then it should NEVER BE DELETED!
3) Are you 100% positive the unknown pointer is a valid memory region? No, then it should NEVER BE DELTED!
In all, there is very little direct work that can be done using an unknown (void*) pointer type. However, indirectly, the void* is a great asset for C++ developers to rely on when data ambiguity is required.
If you just want a buffer, use malloc/free.
If you must use new/delete, consider a trivial wrapper class:
template<int size_ > struct size_buffer {
char data_[ size_];
operator void*() { return (void*)&data_; }
};
typedef sized_buffer<100> OpaqueBuffer; // logical description of your sized buffer
OpaqueBuffer* ptr = new OpaqueBuffer();
delete ptr;
For the particular case of char.
char is an intrinsic type that does not have a special destructor. So the leaks arguments is a moot one.
sizeof(char) is usually one so there is no alignment argument either. In the case of rare platform where the sizeof(char) is not one, they allocate memory aligned enough for their char. So the alignment argument is also a moot one.
malloc/free would be faster on this case. But you forfeit std::bad_alloc and have to check the result of malloc. Calling the global new and delete operators might be better as it bypass the middle man.

Delete on already deleted object : behavior?

I am wondering what will hapen if I try to do a delete on a pointer that is already deleted, or may have not been allocated ? I've read two things : first, that delete operator will do some checkings and we do not need to check if the pointer is null ; and then, I read that it can lead to unknown behaviors..
I'm asking it, because I use some personal objects that contains Qt objects attributes ; I think that Qt delete all widgets associated when we close the window, but I'm not pretty sure and still : if the soft crash before the window's close, we have to delete all objects manually.
So, what would be the best solution ? Something like that ?
if( my_object )
delete my_object;
Can it avoid dangerous behaviours ?
delete on an already deleted non-null pointer is undefined behavior - your program will likely crash. You can safely use delete on a null pointer - it will yield a no-op.
So the real problem is not delete on a null pointer. The real problem is here:
ptr = new Something();
otherPtr = ptr;
delete ptr;
delete otherPtr;
This can happen if you have several pointers to the same object and it is quite dangerous. The possible solutions are:
use smart pointers (no delete in your code) or
only have one designated pointer for controlling each object lifetime and delete at exactly the right time.
if( my_object )
delete my_object;
is redundant. delete on a NULL pointer does nothing. This is guaranteed by the standard.
delete on a pointer that was already deleted causes undefined behavior. That's why you should always remember to assign your pointers to NULL after you delete them:
delete p;
p = NULL;
EDIT: As per the comments, I feel I should specify this. If you have multiple pointers to the same object, the assignment to NULL won't make the delete safe. Regardless, it's better to use smart pointers.
Please note that deleting a pointer does not set it to NULL.
int* i = new int;
*i = 42;
delete i;
delete i; // oops! i is still pointing to the same memory, but it has been deleted already
Deleting a null pointer doesn't do anything, deleting an already deleted object will result in undefined behaviour.
the right way is:
if( my_object )
{
delete my_object;
my_object = NULL;
}
because, calling twice the way it was before will call delete on a deleted pointer.
It results in Undefined Behavior if you call delete on already deleted pointer.
Calling delete on a NULL pointer has no-effect though.
Standard c++03 § 3.7.4.2-3
If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. Otherwise, the value supplied
to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(std::size_t) or operator new(std::size_t, const std::nothrow_-t&) in the standard library, and the value supplied to operator delete[](void*) in the standard library shall be one of the values returned by a previous invocation of either operator new[](std::size_t) or
operator new[](std::size_t, const std::nothrow_t&) in the standard library.
Using RAII & Smart Pointers are your best weapons to avoid such problems.
Just to combine the answers above:
if (my_object) checks the value of the pointer, not the existence of the object. If it is already deleted, the pointer may still point to that location.
deleting an already deleted object is undefined behavior and will probably crash your program.
deleting NULL is defined and does nothing. Together with point 1 this explains the answer of Luchian.
To sum it up: You have to be clear on who owns the object and where the different pointer to the object are. When you delete an object, make sure to set all pointer pointing to that location to 0/NULL. Use managing objects like boost::shared_pointer or QPointer to help you in this task.

Deleting a pointer

In C++, whats the recommended way of deleting a pointer? For example, in the following case, do I need all three lines to delete the pointer safely (and if so, what do they do)?
// Create
MyClass* myObject;
myObject = new MyClass(myVarA, myVarB, myVarC);
// Use
// ...
// Delete
if(myObject) {
delete myObject;
myObject = NULL;
}
No you do not need to check for NULL.
delete takes care if the pointer being passed is NULL.
delete myObject;
myObject = NULL;
is sufficient.
As a general policy, avoid using freestore allocations wherever you can, and if you must use Smart Pointers(RAII) instead of raw pointers.
C++03 Standard Section §3.7.3.2.3:
The value of the first argument supplied to one of the deallocation functions provided in the standard library may be a null pointer value; if so, the call to the deallocation function has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(size_t) or operator new(size_t, const std::nothrow_t&) in the standard library, and the value supplied to operator delete in the standard library shall be one of the values returned by a previous invocation of either operator new or operator new[](size_t, const std::nothrow_t&) in the standard library.
No, you don't need that.
Just write delete p, and be sure to not accept advice about anything else from anyone advocating that you do more.
General advice: avoid raw new and delete. Let some standard container deal with allocation, copying and deallocation. Or use a smart-pointer.
Cheers & hth.,
Best to use a resource-managing class and let the library take care of that for you:
#include <memory>
void foo() // unique pointer
{
std::unique_ptr<MyClass> myObject(new Myclass(myVarA, myVarB, myVarC));
// ...
} // all clean
void goo() // shared pointer -- feel free to pass it around
{
auto myObject = std::make_shared<MyClass>(myVarA, myVarB, myVarC);
// ...
} // all clean
void hoo() // manual -- you better know what you're doing!
{
MyClass * myObject = new MyClass(myVarA, myVarB, myVarC);
// ...
delete myObject; // hope there wasn't an exception!
}
Just to add that setting the pointer to NULL after it's been delete'd is a good idea so you don't leave any dangling pointers around since attempts to dereference a NULL pointer is likely to crash your application straight away (and so be relatively easy to debug), whereas dereferencing a dangling pointer will most likely crash your application at some random point and be much more difficult to track down and fix.

C++ Overload or monitor the dereference operator (on a pointer)

I was wondering if it is possible to add code (checks of the validity of the object pointed to actually) when a pointer is dereferenced.
I saw many subjects on overloading operator ->, but it seems the operator was called on an object, not a pointer. Maybe (probably) there is something I'm misunderstanding.
here's an example :
T* pObj = new T();
pObj->DoStuff(); // call check code (not in DoStuff)
delete pObj;
pObj->DoOtherStuff(); // call check code (not in DoOtherStuff)
the "check code" should be independent from the function (or members) called. My idea was to set a member as an int in the class, and give it a defined value at construction (and destruction), then check the value.
As you may have guess I try to check for invalid pointers used. I try to read the code but it's far too big and complex to not miss many potential errors.
Thanks for your answers and insights.
operator-> can only be overloaded as a member function of a class, not for a normal pointer.
In general there is no way to check that a (non-null) pointer actually points to a valid object. In your example delete pObj; does nothing to change the pointer; it just leaves it pointing to invalid memory, and there is no way to test for that. So, even if you could overload operator-> here, the best it could do is check that it wasn't null.
The usual approach is to use smart pointers, rather than normal pointers. A smart pointer is a class that wraps a plain pointer to an object, and has overloads of operator* and operator-> so that it looks and feels like a pointer. You won't delete the object directly, but through the pointer (when it goes out of scope, or explicitly by calling a reset() function), and the pointer can then set its plain pointer to null when that happens. In that way, the plain pointer will always be either valid, or null, so the overloaded operators can usefully check it before dereferencing.
Smart pointers (and RAII in general) bring other advantages too: automatic memory management, and exception safety. In your code, there will be a memory leak if DoStuff() throws an exception; pObj will go out of scope, and so there will be no way to access it to delete the object it points to. The memory will be lost and, if this keeps happening, you will eventually use all the system's memory and either crash or slow to a crawl. If it were a smart pointer, then the object would be deleted automatically as it went out of scope.
Commonly used smart pointers from the Standard Library and Boost are auto_ptr, scoped_ptr and shared_ptr, each with different behaviour when copying the pointer. C++0x will introduce unique_ptr to replace auto_ptr.
You should overload operators -> and *, in more or less the same way that auto_ptr works.
For example:
template<typename T>
class SafePtr {
public:
SafePtr(T*p) : ptr(p) {}
T &operator*()
{
if ( !preConditions() ) {
throw runtime_error( "preconditions not met" );
}
return *ptr;
}
T * operator->()
{
if ( !preConditions() ) {
throw runtime_error( "preconditions not met" );
}
return ptr;
}
bool preConditions()
{ return ( ptr != NULL ); }
private:
T* ptr;
};
This could be a very basic example. The -> operator would be overloaded in a similar way. All the logic you want to execute before dereferencing the pointer would be coded inside preConditions(). I think that you can get the idea from here, if not, you can ask further.
Hope this helps.
operator -> (or any other operators) can be overloaded only for class objects and not for pointers. For your case, you can think of using standard/cutom Smart Pointers (which are actually objects and not pointer, but they can be used as of they are pointers).
If can not use smart pointers, then make a practice of assigning NULL after delete/free. Or you can use your custom wrapper for delete such as:
template<typename T>
void Destroy (T *&p) // use this wrapper instead of 'delete'
{
delete p;
p = 0;
}
As Nick already pointed out, use std::auto_ptr or better (and if possible) boost::shared_ptr. It basically implements almost exactly what you want.
To answer the question directly: indeed, you can only overload operator-> for a class, so in that case you won't be able to apply it to a pointer of that class. In other words, it will apply to objects, not pointers.
class T {
T& operator->() { }
};
void f() {
T* pObj = new T();
pObj->DoStuff(); // Calls DoStuff, but... Oops! T::operator->() was not called!
(*pObj).DoStuff(); // Equivalent to the above
delete pObj;
(*pObj)->DoStuff(); // T::operator->() is called, but
// there is no improvement here: the pointer is dereferenced
// earlier and since it was deleted, this will "crash" the application
//pObj->->DoStuff(); // Syntactically incorrect, but semantically equivalent
//to the above
pObj->operator->()->DoStuff(); // Semantically equivalent to the above two,
//but avoids the double member access operator.
}

How can this compile? (delete a member of const object)

I would expect an error inside the copy constructor, but this compiles just fine with MSVC10.
class Test
{
public:
Test()
{
p = new int(0);
}
Test(const Test& t)
{
delete t.p; // I would expect an error here
}
~Test()
{
delete p;
}
private:
int* p;
};
This is a common issue with pointers. There is no way of actually disabling code from calling delete on a pointer (other than controlling access to the destructors). The first thing that you can hear is that the delete does not modify the pointer, but rather the pointed object. This can easily be checked by printing the pointer (std::cout << static_cast<void*>(p);) before and after a delete, so even if the pointer is constant the operation is not modifying it.
A little less intuitive is the fact that you can delete a pointer to a constant element --and the delete surely modifies the pointed element. But the language needed to be able to destruct constant objects when they fell out of scope (think { const mytype var(args); }) so const-ness cannot really affect the ability to destroy an object, and if that is allowed for auto variables, it does not make much sense to change the behavior for dynamically allocated objects. So at the end this is also allowed.
The issue that you are running into here is that you are not changing p per se (thus pstays immutable as you're not changing its value), but you're changing what p points to and thus are working at one additional level of indirection. This is possible because deleteing the memory associated with a pointer doesn't change the pointer itself.
In a strict sense the const-ness of the object is preserved, even though its logical constness has been violated as you pulled the rug from underneath whatever p was pointing to.
As JonH mentioned in the comment, if you were not able to delete the object pointed to by a pointer held in a const object, you would end up with memory leaks because you wouldn't be able to clean up properly after the object.
Constants are immutable, but that doesn't guarantee that they cannot be deleted. How would you ever delete an object if delete wasn't allowed.
If you try to modify t.p that should throw an error as t is const. But deleting t is quite normal even if it is constant.
Having:
int* const p;
... does not disallow operator delete from being called on p. Having const int* also does not disallow operator delete from being called on it.
Typical operator delete implementations take void* and any pointer will be implicitly cast to it (actually this might be the standard behavior to take void* or the only reasonable way to implement one global operator delete which can delete anything). Also as an interesting tidbit, one can implement their own overloaded operator delete (either globally or per-class) which takes void* and only has to free the memory allocated by new. The destructor call is implicitly added before any call to operator delete by the compiler; operator delete does not call the dtor in its implementation.
It is also worth noting that having const Test& in this case basically modifies the member, int* p so that it's analogous to int* const p, not int const* p or const int* p.
Thus:
Test::Test(const Test& other)
{
*other.p = 123; // this is valid
other.p = NULL; // this is not valid
}
In other words, the pointer address is immutable, but the pointee is not. I've often encountered a lot of confusion here with respect to member function constness and the effect it has on data members which are pointers. Understanding this will give a little insight as to one of the reasons why we need the separation between iterator and const_iterator.