Search code examples
c++warnings

How to avoid deprecated-copy warnings?


Here is some simplified code. It's not mine, but I'm adapting it for a project of mine. It's part of a sizeable codebase I'm importing, and which I don't want to change more than absolutely necessary.

void function (object& out_thing)
{
 object thing;
#pragma omp nowait
 for (int k = 0 ; k < 5 ; k++) {
  object* things[2];
  float scores[2];
  for (i = 0; i < 2 ; i++)
   scores[i] = evaluateThings(things[i], parameter1, parameter2);
   if (scores[1] < scores[0]) {
    scores[0] = scores[1];
    things[0] = things[1];
   }
  thing = *(things[0]);
 }
 out_thing = thing;
}

When compiled, I get warnings that the implicitly declared thing = *(things[0]) and out_thing = thing are deprecated [-Wdeprecated-copy] because I have a user-provided copy constructor.

I guess the compiler wants me to write object thing(*(things[1]) but I can't because I need to declare object thing before the omp pragma, and I can't write object out_thing(thing) at the end because out_thing is already defined as one of the arguments passed to the function.

Is there any way to recode this to get rid of the warnings?

(I can actually get rid of the first one by changing object thing; to object* thing = NULL and then later on changing thing = *(things[0]); to thing = things[0]; but that requires me to change out_thing = thing; to out_thing = *thing; and I still get the warning for that deprecated copy; I'd like to get rid of both, ideally, if it's possible without extensive changes elsewhere in the code base and without being harmful to performance etc.)


Solution

  • The warning -Wdeprecated-copy warns about a missing/deleted user-declared copy assignment operator, when there is the user-declared destructor ~object. If there is a user-declared destructor, missing a copy constructor or a copy assignment operator is likely the error in the code. You should add a custom copy assignment operator

    object& operator=(const object&);
    

    See What is The Rule of Three?.