Main Content

AUTOSAR C++14 Rule A3-1-6

Trivial accessor and mutator functions should be inlined

Since R2020b

Description

Rule Definition

Trivial accessor and mutator functions should be inlined.

Rationale

Inlined functions avoid the run-time overhead of function calls but can result in code bloat. If an accessor (getter) or mutator (setter) method is trivial, code bloat is not an issue. You can inline these methods to avoid the unnecessary overhead of function calls. You can also avoid repeating several syntax elements inside and outside the class definition.

Methods defined inside classes are implicitly considered as inlined methods. You can inline methods defined outside classes explicitly by using the inline keyword.

Polyspace Implementation

To determine if a method is trivial, the checker uses this criteria:

  • An accessor method is trivial if it has no parameters and contains one return statement that returns a non-static data member or a reference to a non-static data member.

    The return type of the method must exactly match or be a reference to the type of the data member.

  • A mutator method is trivial if it has a void return type, one parameter, and contains one assignment statement that assigns the parameter to a non-static data member.

    The parameter type must exactly match or be a reference to the type of the data member.

The checker flags trivial accessor and mutator methods defined outside their classes without the inline keyword.

The checker does not flag template methods or virtual methods.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

class PhysicalConstants {
    public:
       double getSpeedOfLight() const;
       void setSpeedOfLightInMedium(double newSpeed);
       double getRefractiveIndexGlass() { //Compliant
           return refractiveIndexGlass;
       }
    private:
       double speedOfLight;
       double refractiveIndexGlass;
};

double PhysicalConstants::getSpeedOfLight() const{ //Noncompliant
    return speedOfLight;
}

void PhysicalConstants::setSpeedOfLightInMedium(double newSpeed) {//Noncompliant
    speedOfLight = newSpeed;
}

In this example, the accessor methods getSpeedOfLight and getRefractiveIndexGlass are trivial. The getSpeedOfLight method is defined outside its class and is noncompliant. The getRefractiveIndexGlass method is defined inside the class definition and complies with the rule.

The trivial mutator method setSpeedOfLightInMedium is also defined outside the class definition and violates the rule.

Check Information

Group: Basic concepts
Category: Advisory, Automated

Version History

Introduced in R2020b

Go to top of page