Title
unary_function and binary_function should have protected nonvirtual destructors
Status
nad
Section
[depr.base]
Submitter
Joe Gottman

Created on 2004-08-19.00:00:00 last changed 164 months ago

Messages

Date: 2010-10-21.18:28:33

Rationale:

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

Date: 2010-10-21.18:28:33

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() {}
    };
Date: 2004-08-19.00:00:00

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.

History
Date User Action Args
2010-10-21 18:28:33adminsetmessages: + msg2792
2010-10-21 18:28:33adminsetmessages: + msg2791
2004-08-19 00:00:00admincreate