Contents

C++ quick tips: Deleted free functions

I’m sure that we all know about the = delete keyword introduced in c++11 and its application to class member functions. I’m not sure though if everyone knows that = delete can be applied to free standing functions as well.

Main reason to have this feature is to limit the number of overloads and narrow down implicit conversion. std::cref and std::ref are a good example. cppreference for std::ref lists several overloads. The following are deleted:

1
2
3
4
5
template< class T >
void ref( const T&& ) = delete;
...
template< class T >
void cref( const T&& ) = delete;

This is to prevent overload resolution to accept incovations like:

1
auto rw = std::ref(123);

So, attempts to use std::ref or std::cref with rvalues is basically forbidden as it would result in undefined behaviour.

= delete usage is not limited only to function overloads! There’s nothing preventing us from using it on any function.

Consider the following:

1
2
3
4
5
6
int printf(const char * format, ...) = delete;

int main() {
    printf("hello world");
    return 0;
}

The above will result in build error:

1
2
3
4
delete.cpp: In function ‘int main()’:
delete.cpp:6:11: error: use of deleted function ‘int printf(const char*, ...)’
    6 |     printf("hello world");
      |     ~~~~~~^~~~~~~~~~~~~~~

Following the = delete declaration, usage of printf has been effectively forbidden.

Let’s not forget though that this is a hack since printf is declared more than once and compiler will, rightly so, complain about this fact as well:

1
2
3
4
5
6
7
delete.cpp:3:5: warning: deleted definition of ‘int printf(const char*, ...)’ is not first declaration
    3 | int printf(const char * format, ...) = delete;
      |     ^~~~~~
In file included from /usr/include/c++/13.1.1/cstdio:42,
                 from delete.cpp:1:
/usr/include/stdio.h:356:12: note: previous declaration of ‘int printf(const char*, ...)’
  356 | extern int printf (const char *__restrict __format, ...);