Search code examples
c++functionc++17delete-operator

Why delete a non-member function?


This is about non-member functions. I do understand this as an implementation. But I have a bit of puzzlement with the logic behind?

     // why this?
     void do_not_use_this_ever ( void ) = delete ;

If I do not want a function to be used, why declare it and then delete it? Why not just:

     // why not this?
     // void do_not_use_this_ever ( void ) = delete ;

If = delete declares an intent, just a comment like above declares the same intent.

Can anyone think of a use-case where declaring a non-member function as deleted is better then not have it at all?

Update

Already answered here . Although. Both answers use std::cref as an example. As @geza said in the comment to his answer, it would be rather beneficial to discuss other use cases as well.


Solution

  • Deleting a non-member function can be useful to disable a function with certain parameters. For example, here is std::cref:

    template< class T >
    std::reference_wrapper<const T> cref( const T& t ) noexcept;
    template <class T>
    void cref(const T&&) = delete;
    

    cref is used to convert an object reference to reference_wrapper. This can be used for example with std::bind: std::bind parameters are copied into the resulting object. But with cref, it becomes just a reference. So, cref must not be used with temporary parameters.

    If the second overload wasn't deleted, then for example, cref(2) would be a valid expression (as a temporary can be bound to a const reference). This is a problem, as cref would return a reference to an object which will be destroyed. To disallow this, we need to delete functions where cref is passed a temporary, and this is what the second deleted overload does.