To get a trial key
fill out the form below
Team License (standard version)
Enterprise License (extended version)
* By clicking this button you agree to our Privacy Policy statement

** This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
Request our prices
New License
License Renewal
--Select currency--
USD
EUR
GBP
RUB
* By clicking this button you agree to our Privacy Policy statement

** This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
Message submitted.

Your message has been sent. We will email you at


If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

>
>
>
V818. It is more efficient to use an in…
Analyzer Diagnostics
General Analysis (C++)
General Analysis (C#)
General Analysis (Java)
Diagnosis of micro-optimizations (C++)
Diagnosis of 64-bit errors (Viva64, C++)
MISRA errors
AUTOSAR errors
Additional information
Contents

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

June 1, 2017

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
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site.
Learn More →
Accept