0

I am trying to run this example in https://en.cppreference.com/w/cpp/language/copy_assignment, but when I delete the default constructor and default copy constructor: A() = default; A(A const&) = default;, clang++ says that warning: definition of implicit copy constructor for 'A' is deprecated because it has a user-provided copy assignment operator [-Wdeprecated-copy-with-user-provided-copy].

My question is that I have called copy assignment instead of copy constructor, why clang++ reports copy constructor warning?

Here is my code:

#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
 
struct A
{
    int n;
    std::string s1;

    // user-defined copy assignment (copy-and-swap idiom)
    A& operator=(A other)
    {
        std::cout << "copy assignment of A\n";
        std::swap(n, other.n);
        std::swap(s1, other.s1);
        return *this;
    }
};
 
int main()
{
    A a1, a2;
    std::cout << "a1 = a2 calls ";
    a1 = a2; // user-defined copy assignment
}

Here is cppinsight link, I can see there is an inline copy constructor in struct A.

struct A
{
  int n;
  std::basic_string<char> s1;
  inline A & operator=(A other)
  {
    std::operator<<(std::cout, "copy assignment of A\n");
    std::swap(this->n, other.n);
    std::swap(this->s1, other.s1);
    return *this;
  }
  
  // inline A(const A &) noexcept(false) = default;
  // inline ~A() noexcept = default;
  // inline A() noexcept = default;
};
aki
  • 25
  • 4

1 Answers1

0

This invokes A's copy constructor since other is a value copy.

inline A & operator=(A other)

Change it to

inline A & operator=(const A& other)

Then drop the swaps and simply assign other's member variables to *this

n=other.n;
s1=other.s1;

This removes the requirement for a copy constructor. However, defining an assignment operator w/o also defining a copy constructor violates the rule of three hence the compiler warning. Also, "inline" is intrinsic when the member function is defined in the class.

doug
  • 3,840
  • 1
  • 14
  • 18
  • 3
    They're looking to use a [copy-and-swap idiom](https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom), so I'm guessing the copy and the swap is desired. – Etienne de Martel Jan 16 '22 at 06:51
  • 3
    the reason of the error is described correctly, but the suggestion should be "put the copy constructor back". – n. m. could be an AI Jan 16 '22 at 07:20
  • It looked like the OP didn't understand copy and swap requires the copy constructor so, since the assignment operator can be implemented w/o ctor, it would be useful for learning to remove the requirement. Baby steps. – doug Jan 16 '22 at 17:56