Main Content

Public static field not const

A static and public field of a struct or class is not marked as a const

Since R2022a

Description

This defect occurs when all of these conditions are true:

  • A class contains a data member that is both static and public

  • The static and public data member is not const

Risk

The public static data members of a class can be modified by any of class in the program. Unless public static data members are specified as const, they might be modified in unexpected ways and result in bugs that are difficult to diagnose.

Fix

To resolve this defect, specify the public static data members as const or constexpr.

Examples

expand all

#include<string>
class SomeAppClass {

private:
	static std::string appPropertiesConfigFilep2; 
	
protected:
	static std::string appPropertiesConfigFilepr2; 
	
public:
	static std::string appPropertiesConfigFile2; //Defect
	
	static void foo() {}          
	int bar() {
		static int v = 3;
		return v;
	}
};

In this example, the data member appPropertiesConfigFile2 is static and public, but not const. Polyspace® flags the member. The static data members that are private and protected are not flagged. This rule does not apply to static objects that are in the scope of public member functions of a class.

Correction — Declare public static Data Members as const

To resolve this defect, declare the public static data members of a class as const.

#include<string>
class SomeAppClass {

private:
	static std::string appPropertiesConfigFilep2; 
	
protected:
	static std::string appPropertiesConfigFilepr2; 
	
public:
	static const std::string appPropertiesConfigFile2; //No Defect
		
	static void foo() {}          
	int bar() {
		static int v = 3;
		return v;
	}
};

Result Information

Group: Good practice
Language: C++
Default: Off
Command-Line Syntax: PUBLIC_STATIC_FIELD_NOT_CONST
Impact: Low

Version History

Introduced in R2022a