Delete overload in C++

By , last updated November 3, 2021

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.


unique_ptr(const unique_ptr&) = delete;
unique_ptr& operator=(const unique_ptr&) = delete;

Use “= delete” to remove a certain overload

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
}

Comments

Be the first to comment.

Leave a Reply


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*