[cfe-dev] problem with std::function and virtual destructor
Steve Ramsey
clang at lucena.com
Sun Jul 15 10:38:13 PDT 2012
On Jul 15, 2012, at 12:59 AM, Richard Smith wrote:
> On Sat, Jul 14, 2012 at 11:40 PM, Rich E <reakinator at gmail.com> wrote:
>> Can anyone explain why the following doesn't compile?
>>
>> #include <functional>
>>
>> struct X{
>> typedef std::function<void(X&)> callback_type;
>> virtual ~X() {}
>> private:
>> callback_type _cb;
>> };
>>
>> int main(){}
>>
>>
>> If you comment out the virtual destructor, the code compiles fine. Full error report:
>
> I'm not sure why instantiating std::function<void(X&)>::operator= would require X to be complete -- libstdc++ does not behave that way. It's possible this is a bug in libc++, but it's also possible that the standard allows this behavior and libstdc++ is just more permissive. Hopefully Howard can help with that part.
This is correct behavior as per FDIS 12.8.18. Specifically, since there's a user-declared copy constructor, there needs to be a user-declared copy-assignment operator, if you want one; otherwise, the implicitly declared one is defined as deleted. Consider:
//////////
#include <functional>
struct X{
typedef std::function<void(X&)> callback_type;
virtual ~X() {}
// X & operator = (const X &) = default;
private:
callback_type _cb;
};
int main(){}
/////////
Uncommenting the copy-assignment operator function declaration makes the error go away. Note that in this case, the copy constructor is deleted, and the default constructor, move constructor, and move-assignment operator are suppressed.
Steve
More information about the cfe-dev
mailing list