V820. The variable is not used after copying. Copying can be replaced with move/swap for optimization.


The analyzer has detected a variable that is copied to another variable but is never used after that. Such code can be optimized by removing the unnecessary copy operation.

We will discuss a few examples of such code. Example 1:

class UserInfo
{
  std::string m_name;
public:
  void SetName(std::string name)
  {
    m_name = name;
  }
};

In this code, two copy operations take place: the first is executed when calling the 'SetName()' function; the second when copying 'name' to 'm_name'. You can eliminate the unnecessary copy operation by using a move assignment operator:

void SetName(std::string name)
{
  m_name = std::move(name);
}

If the object is not move assignable, change the signature of the 'SetName()' function by making the 'name' variable a constant reference. In this case, copying will be performed only when the assignment operation is executed.

void SetName(const std::string &name)
{
  m_name = name;
}

Example 2:

bool GetUserName(int id, std::string &outName)
{
  std::string tmp;
  if (db->GetUserName(id, tmp))
  {
    outName = tmp;
    return true;
  }
  return false;
}

This code contains local variable 'tmp', which is copied to 'outName' and is not used after that. From the performance viewpoint, using 'move' or 'swap' is more preferable.

bool GetName(int id, std::string &outName)
{
  std::string tmp;
  if (db->GetUserName(id, tmp))
  {
    outName = std::move(tmp);
    return true;
  }
  return false;
}

Example 3:

void Foo()
{
  std::vector<UserInfo> users = GetAllUsers();
  {
    std::vector<UserInfo> users1 = users;
    DoSomethingWithUsers1(users1);
  }
  {
    std::vector<UserInfo> users2 = users;
    DoSomethingWithUsers2(users2);
  }
}

Copying can sometimes be replaced with a reference if the previous solution (swap/move) is not available to some class. This might not be the neatest solution, but it is certainly a faster one.

void Foo()
{
  std::vector<UserInfo> users = GetAllUsers();
  {
    std::vector<UserInfo> users1 = users;
    DoSomethingWithUsers1(users1);
  }
  {
    std::vector<UserInfo> &users2 = users;
    DoSomethingWithUsers2(users2);
  }
}

Bugs Found

Checked Projects
334
Collected Errors
12 668