C++11 introduced a way to disable (delete) methods from being used. It is mostly used to delete certain operators. The classic case is the implementation of std::unique_ptr
. The copy constructor and assignment operator are deleted, so it is not possible to copy a unique pointer.
This is a sample from an implementation of a unique_ptr
, where the copy constructor and assignment operator are deleted.
In certain code bases of a certain age, there may be many uses of const char *
used as parameters to methods. Changing foo(const char *)
to foo(const std::string &)
is legal. std::string
contains an implicit constructor accepting const char *
, which automatically constructs a std::string
.
However, from the call sites, when calling this method with a string object, the method .c_str()
had to be passed to be able to call foo(...)
.
void foo(const std::string &)
{
// implementation
}
std::string parameter = "parameters";
foo(parameter.c_str());
But when changing the signature from foo(const char *)
to foo(const std::string &)
, the call site above would send a const char *
to foo()
, and it would be implicitly converted to std::string
. Depending on the size of the string, it can be expensive with regards to heap allocation and deallocation.
Recently I discovered = delete
is not limited to constructors and operators, but it can be used elsewhere too.
To disable the implicit conversion from const char *
to std::string
, the const char *
overload must be explicitly deleted.
#include <string>
void foo(const std::string &)
{
// implementation
}
void foo(const char *) = delete; // Deletes the "const char *" overload
int main()
{
std::string parameter = "parameters";
foo(parameter.c_str()); // error C2280: 'void foo(const char *)': attempting to reference a deleted function
foo(parameter); // OK
}