>
>
>
V818. It is more efficient to use an in…


V818. It is more efficient to use an initialization list rather than an assignment operator.

The analyzer has detected that there is a constructor implemented in a suboptimal way and that the code performing member initialization could be optimized.

Consider the following example:

class UserInfo
{
  std::string m_name;
public:
  UserInfo(const std::string& name)
  {
    m_name = name;
  }
};

The 'm_name' member is first initialized as an empty string and only then is the string from the 'name' variable copied into it. In C++03, this will lead to additional memory allocation for the empty string. The least you can do to improve this code is to call the copy constructor immediately using an initialization list.

UserInfo(const std::string& name) : m_name(name)
{
}

In C++11, you could go even farther. The next example shows how object UserInfo could be constructed:

std::string name = "name";
UserInfo u1(name);           // 1 copy
UserInfo u2("name");         // 1 ctor, dtor + 1 copy
UserInfo u3(GetSomeName());  // 1 copy

If the strings are long enough to avoid Small String Optimization, this code will perform unnecessary memory allocation and copy operations. To avoid this, pass the argument by value:

UserInfo(std::string name) : m_name(std::move(name))
{
}

After that, no unnecessary copies will be created by temporary values thanks to the move constructor.

std::string name = "name";
UserInfo u1(name);             // 1 copy + 1 move
UserInfo u2("name");           // 1 ctor, dtor + 1 move
UserInfo u3(GetSomeName());    // 2 move
UserInfo u4(std::move(name));  // 2 move