Would this constructor be an acceptable practice?

Suppose I have a C ++ class that correctly implements the copy constructor and the overloaded = operator. Properly implemented, I mean that they work and do a deep copy:

Class1::Class1(const Class1 &class1)
{
  // Perform copy
}
Class1& Class1::operator=(const Class1 *class1)
{
  // perform copy
  return *this;
}

Now let's say that I have this constructor:

Class1::Class1(Class1 *class1)
{
   *this = *class1;
}

My question is, can the above constructor be an acceptable practice? This is the code that I inherited and maintained.

+3
source share
4 answers

I would say no for the following reasons:

  • The traditional copy constructor takes its argument as a reference to const, and not as a pointer.
  • , const Class1*, , .
  • ( !), Class1 , operator=
  • operator= ; , .

" " operator= . .

+7

.

, .

, , , .

, , , ?

+2

, , , , . , ( ), . , .

+2

- . , , , ( const refs, , / ). , , - . , , , , .

, , , , , , .

I cannot come up with any good reason why you would like to make the conversion between a pointer to a type and the type itself implicit or even explicit. The built-in way to do this is to dereference an object. I believe that there may be some set of specific circumstances that I can’t think of where it might be needed or a good idea, but I really doubt it. Of course, I would strongly advise you to do this if you do not have concrete and compelling reasons for this.

+1
source

Source: https://habr.com/ru/post/1743543/


All Articles