0

The following code doesn't compile -

struct A {
    A() = default;
    A(const A& other) = delete;
};


int main()
{
  auto a = A();
  auto u = std::make_unique<A>(std::move(a));
}

While the following does -

struct A {
    A() = default;
    A(const A& other) = delete;
    A(A&& other) = default;
};

int main()
{
  auto u = std::make_unique<A>(A());
}

The error I got is call to implicitly-deleted copy constructor.
Im using a blaze compiler for cpp-17.

Why does the first code segment not compile? It shouldn't use the copy contractor, just the move one.

Edit:
Adding A(A&& other) = default; solves the issue. Does this mean that deleting the copy-contractor also deletes the move-contractor implicitly, and it needs to be added?

Nimrod Fiat
  • 473
  • 3
  • 12
  • 2
    You don't declare the move constructor. See when [**Implicitly-declared move constructor**](https://en.cppreference.com/w/cpp/language/move_constructor), neither of them is your case, because you have a user declared deleted copy constructor. – 273K Dec 05 '22 at 16:32
  • 3
    Your second code block also does not compile: http://coliru.stacked-crooked.com/a/40d5fc3c9e95fd0f – NathanOliver Dec 05 '22 at 16:32
  • interesting @NathanOliver, because in https://cpp.sh/ the code does compile (with the include). I don't know which compiler you are using but it probably isn't blaze. And even if both shouldn't compile, then why shouldn't they? what is the issue? – Nimrod Fiat Dec 05 '22 at 16:36
  • 2
    Can't reproduce: When I add `A(A&& other) = default;` (to your first example) the code compiles. – Adrian Mole Dec 05 '22 at 16:37
  • With proper includes, and adding defaulted move constructor, [the first code block compiles just fine](https://godbolt.org/z/P6f6aTjb7) on modern GCC and clang (not that it does anything useful; even `-O1` reduces it to `return 0;`). – ShadowRanger Dec 05 '22 at 16:41
  • @NimrodFiat it compiles because you have `A(A&& other) = default;` in code shown in your comment. (In your question that `A(A&& other) = default;` is missing) – t.niese Dec 05 '22 at 16:41
  • you are right, i'll fix the question. if i add A(A&& other) = default; it does solve the problem. – Nimrod Fiat Dec 05 '22 at 16:45

1 Answers1

3

By deleting the copy constructor, you also implicitly delete the move constructor (A(A&& other)). If you want to use the first code segment, you must define your own custom move constructor (which will depend on the actual data of A).

Look at the concepts "rule of 5", "rule of 0" and related links (e.g. here) to get a grip on which constructors must be defined.

(by the way, the second code block does not compile on GCC or Clang, as pointed out in the comments. See godbolt. Edit: code in question was changed so this comment is no longer true.)

Adomas Baliuka
  • 1,384
  • 2
  • 14
  • 29