The vulnerability as described in ISO/IEC 24772-1:2024 6.20 exists in C++, except for the second issue of limited identifier length.
In C++ all characters in an identifier are significant.
In C++ the same name can be used for different functions as long as they have distinct parameters or different scopes where they are defined.
See also 4.3 Name Lookup and Overload Resolution.
Using directives don’t import a name to the current scope. Only names not found in the current or its surrounding scopes up to the common scope shared with the namespace in the using directive will be made accessible.
namespace NS1 {
int const a{1};
}
namespace NS2{
int const a{2};
void foo(){
using namespace NS1; // attempt to access NS1::a
std::cout << a; // prints 2
}
}
In a lambda expression only identifiers are accessible that captured from the surrounding scopes, because the scope of a lambda expression is not nested within its surrounding scope. Variables with static storage duration or constexpr variables are also accessible, because they allow the lambda to be returned from its current scope without dangling. Some special rules apply for lambdas in member functions when capturing this with respect to the member functions. Lambda capture defaults [&] or [=].{cpp} carry the risk to accidentally access an unintended variable from the outer scopes.
int a1{0};
void bar(){
constexpr int b{42};
int a2{3};
[](){ // ok to use std::cout because its global
std::cout << a1; // typo prints 0
std::cout << b; // constexpr OK
}();
auto lam=[=](){
std::cout << a2;
};
{
int a2{4};
[a2](){
std::cout << a2; // prints 4
}();
lam(); // prints 3
}
}
To avoid the vulnerability or mitigate its ill effects, C++ software developers can:
Apply the avoidance mechanisms of ISO/IEC 24772-1:2024 6.20.5, with the exclusion of guidance related to truncated identifiers.
Qualify names to disambiguate potential conflicts between names introduced from different scopes.
Use modern integrated development environments that inform about the declaration of any identifier occurrence.
Enable compiler diagnostics that inform about the hiding of declarations.