Search code examples
c++c++11assignment-operator

explicitly-defaulted copy assignment operator must return MyClass &


// Task.h
class Task
{
public:
    Task() = default;
    Task(const Task &) = delete;
    ~Task() = default;
    Task(Task &&) = default;
    const Task & operator= (const Task &) = default;
};


/main.cpp
#include <iostream>
#include "Task.h"

int main()
{
    Task t;
    std::cout<<"hello world"<<std::endl;
    return 0;
}

I'm coding c++ on Mac OS. When I compile the code above: g++ main.cpp, I get the error as below:

error: explicitly-defaulted copy assignment operator must return 'Task &'

I don't understand at all. operator= can ONLY return non-const reference here? I executed the same code in Windows and it worked without any error. So Mac OS has some special c++ standard?


Solution

  • The problem is that I use = default.
    http://en.cppreference.com/w/cpp/language/copy_assignment

    If = default is used, the type of return must be non-const reference. Whereas if we code like this: const Task & operator= (const Task &t){}, it works without any error.