Pour obtenir une clé
d'essai remplissez le formulaire ci-dessous
Demandez des tariffs
Nouvelle licence
Renouvellement de licence
--Sélectionnez la devise--
USD
EUR
RUB
* En cliquant sur ce bouton, vous acceptez notre politique de confidentialité

Free PVS-Studio license for Microsoft MVP specialists
To get the licence for your open-source project, please fill out this form
** En cliquant sur ce bouton, vous acceptez notre politique de confidentialité.

I am interested to try it on the platforms:
** En cliquant sur ce bouton, vous acceptez notre politique de confidentialité.

Votre message a été envoyé.

Nous vous répondrons à


Si vous n'avez toujours pas reçu de réponse, vérifiez votre dossier
Spam/Junk et cliquez sur le bouton "Not Spam".
De cette façon, vous ne manquerez la réponse de notre équipe.

>
>
>
V1043. A global object variable is decl…
Analyzer diagnostics
General Analysis (C++)
General Analysis (C#)
General Analysis (Java)
Diagnosis of micro-optimizations (C++)
Diagnosis of 64-bit errors (Viva64, C++)
Customer specific requests (C++)
MISRA errors
AUTOSAR errors
OWASP errors (C#)
Problems related to code analyzer
Additional information
Contents

V1043. A global object variable is declared in the header. Multiple copies of it will be created in all translation units that include this header file.

21 Aoû 2019

The analyzer has detected a declaration of a constant object in a header file. Including this file using the 'include' directive will result in creating multiple copies of that object. If the class has a constructor, it will be called each time the header is included, which may have undesirable side effects.

For example:

//some_header.h

class MyClass
{
  int field1;
  int field2;
  MyClass (int a, int b)
  {
    // ....
  }
};

// ....

const MyClass object{1, 2}; // <=

The diagnostic ignores classes and structures with no constructors defined. The following code snippet will not trigger the warning:

//some_header.h

struct MyStruct
{
  int field1;
  int field2;
};

// ....

const MyStruct object{1, 2};

You can also avoid this error by declaring the variable as 'inline' (starting with C++17) or 'extern'. With this fix, the variable initialization and constructor call will be performed only once.

Fixed version:

//some_header.h

class MyClass
{
  // ....
};

// ....

inline const MyClass object{1, 2};

Note: using the 'constexpr' keyword instead of 'const' in the variable declaration doesn't change this behavior. According to the C++17 standard, only constexpr functions and static constexpr class/structure fields are implicitly declared as inline.

This issue is discussed in detail in the article "What Every C++ Developer Should Know to (Correctly) Define Global Constants".

Unicorn with delicious cookie
Nous utilisons des cookies pour améliorer votre expérience de navigation. En savoir plus
Accepter