This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of NAD status.

480. unary_function and binary_function should have protected nonvirtual destructors

Section: 99 [depr.base] Status: NAD Submitter: Joe Gottman Opened: 2004-08-19 Last modified: 2016-01-28

Priority: Not Prioritized

View all other issues in [depr.base].

View all issues with NAD status.

Discussion:

The classes std::unary_function and std::binary_function are both designed to be inherited from but contain no virtual functions. This makes it too easy for a novice programmer to write code like binary_function<int, int, int> *p = new plus<int>; delete p;

There are two common ways to prevent this source of undefined behavior: give the base class a public virtual destructor, or give it a protected nonvirtual destructor. Since unary_function and binary_function have no other virtual functions, (note in particular the absence of an operator()() ), it would cost too much to give them public virtual destructors. Therefore, they should be given protected nonvirtual destructors.

Proposed resolution:

Change Paragraph 20.3.1 of the Standard from

    template <class Arg, class Result>
    struct unary_function {
        typedef Arg argument_type;
        typedef Result result_type;
    };

    template <class Arg1, class Arg2, class Result>
    struct binary_function {
        typedef Arg1 first_argument_type;
        typedef Arg2 second_argument_type;
        typedef Result result_type;
    };

to

    template <class Arg, class Result>
        struct unary_function {
        typedef Arg argument_type;
        typedef Result result_type;
    protected:
        ~unary_function() {}
    };

    template <class Arg1, class Arg2, class Result>
    struct binary_function {
        typedef Arg1 first_argument_type;
        typedef Arg2 second_argument_type;
        typedef Result result_type;
    protected:
        ~binary_function() {}
    };

Rationale:

The LWG doesn't believe the existing definition causes anybody any concrete harm.