Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reassigning std::bind using auto: which compiler gets it right?

MSVC compiles the following code, while GCC and Clang don’t.

#include <iostream>
#include <functional>

class Class
{
    public:
        void display() { std::cout << "display" << std::endl; }
        void store() { std::cout << "store" << std::endl; }
};

int main()
{
    Class instance;
    // std::function<void(void)> f; // this will work
    auto f = std::bind(&Class::display, instance);
    f();
    f = std::bind(&Class::store, instance);
    f();
}

Godbolt conformance view

It seems that GCC and Clang have the copy assignment operator deleted.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Which compilers get it more correct from a standard point of view?

>Solution :

I don’t have the exact wording in the standard, but the compiler error together with cppreference give a pretty good idea of what is happening:

According to the standard, the implicitly defined copy constructor is deleted, if the class implements a move constructor. If a default copy constructor exists, it will not be deleted https://en.cppreference.com/w/cpp/language/copy_constructor.

The return type of std::bind is an unspecified copy-constructible type (if all arguments are copy-constructible) and move-constructible otherwise. https://en.cppreference.com/w/cpp/utility/functional/bind.

So I suppose all compilers are correct in having freedom for the unspecified part of the standard.

On a side note, I would capture the instance in a lambda instead of using std::bind.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading