0

Given the following code snippet, why isn't the copy assignment operator chosen?

It doesn't compile complaining about the copy constructor being deleted. I tried with a user declared assignment operator, but it still didn't work. So it isn't an implicit generation rule being broken (which would prevent =default to work).

struct obj {
    obj() = default;
    ~obj() = default;

    obj(const obj&) = delete;
    obj(obj&&) = default;

    obj& operator=(const obj&) = default;
    // obj& operator=(const obj&) {return *this;} // nada
    obj& operator=(obj&&) = default;

    int t{42};
};

int main(int, char**) {
    obj o1;
    obj o2 = o1; // <-- problem is here

    // but this is ok
    obj o3;
    o3.operator=(o1);

    // or this
    obj o4;
    o4 = o1;
}

Here is a godbolt example : https://godbolt.org/z/MkZuGs

I tried a couple compilers. My guess is somehow, the declaration has to call the copy constructor, but I just don't see how or why.

scx
  • 3,221
  • 1
  • 19
  • 37
  • 1
    This is [copy initialization syntax](https://en.cppreference.com/w/cpp/language/copy_initialization), not an assignment operator invokation. Presense of `=` is misleading. – user7860670 Apr 26 '19 at 17:53
  • OK, thanks. Is it possible to enforce the assignement operator at the call site? – scx Apr 26 '19 at 17:55
  • No, initialization is all about constructor invocation, it never invokes assignment operator. Actually you should always initialize using direct list initialization syntax like `obj o2{o1};` – user7860670 Apr 26 '19 at 17:57

0 Answers0