Main Content

Lambda used as typeid operand

typeid is used on lambda expression

Description

This defect occurs when you use typeid on a lambda expression.

Risk

According to the C++ Standard, the type of a lambda expression is a unique, unnamed class type. Because the type is unique, another variable or expression cannot have the same type. Use of typeid on a lambda expression indicates that you expect a second variable or expression to have the same type as the operand lambda expression. Using the type of a lambda expression in this way can lead to unexpected results.

typeid returns the data type of its operand. Typically the operator is used to compare the types of two variables. For instance:

(typeid(var1) == typeid(var2))
compares the types of var1 and var2. This use does not apply to a lambda expression, which has a unique type.

Fix

Avoid using the typeid operator on lambda expressions.

Examples

expand all

#include <cstdint>
#include <typeinfo>
 
 void func()
 {
 auto lambdaFirst = []() -> std::int8_t { return 1; };
 auto lambdaSecond = []() -> std::int8_t { return 1; };

 if (typeid(lambdaFirst) == typeid(lambdaSecond))  
     {
     // ...
     }
 }

The use of typeid on lambda expressions can lead to unexpected results. The comparison above is false even though lambdaFirst and lambdaSecond appear to have the same body.

Correction – Assign Lambda Expression to Function Object Before Using typeid

One possible correction is to assign the lambda expression to a function object and then use the typeid operator on the function objects for comparison.

#include <cstdint>
#include <functional>
#include <typeinfo>

 void func()
 {
 std::function<std::int8_t()> functionFirst = []() { return 1; };
 std::function<std::int8_t()> functionSecond = []() { return 1; };

 if (typeid(functionFirst) == typeid(functionSecond)) 
     {
     // ...
     }
 }

Result Information

Group: Object Oriented
Language: C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: LAMBDA_TYPE_MISUSE
Impact: Low

Version History

Introduced in R2019b