In C++, the delete
keyword is used in two different situations, depending on the context:
delete
operator can be used to free dynamically allocated memory:When you dynamically allocate memory using
new
, you need to free that memory when you no longer need it to avoid memory leaks. Thedelete
operator is used to free dynamically allocated memory. On the other hand, for automatic use, you can (and should always use) smart pointers.
delete
operator for functions:When you declare a function using delete
, you are declaring that this function is deleted and cannot be used. This is useful for classes with member functions that you want to prevent from being called or inherited.
Suppose you have this function below: print_num(int)
which takes the primitive type int
as a parameter:
When calling this function, note that we can pass the types: char
, bool
and float
/double
that it will receive normally:
When compiling, note that it will work normally:
To avoid this overhead we use the delete
statement to nullify some types:
In this case, the types char
and float
/double
will already receive an error when compiling:
Remembering that
float
/double
will already receive a warning(if you are using an LSP), but it will compile normally!
We can also use the bool
type to not overload:
Therefore, in order to compile our code, we will need to comment the lines referring to the code above, leaving the following at the end:
template
, making it like a boss!:In summary, within this context, Deleting functions in C++:
delete
= “I prohibit this” or “This does not exist”For more information access here.