C & C++

C & C++

By DeepSource

Found global non-const reference or pointer exposing non-const variable CXX-W2011

Anti-pattern

Global variables are accessible anywhere in the scope of the program even in the threads outside of the main thread, as long as it shares the main process stack. Making non-const variables accessible globally is considered quite risky, as they can lead to data races or contention issues.

Consider passing references to unique values and then merging them as if you need mutable stack of program memory. Or use thread-safe singleton pattern to allow for safer access to such variables.

Bad practice

namespace not_global {
    int counter = 0;
}
int& global_counter = not_global::counter; // a non-const reference providing access to a non-const global variable.
void foo() {
    global_counter += 1;
}
int main() {
    global_counter += 1;
    std::thread t(foo);
    t.join();
}

Recommended

#include <thread>

int main() {
    int global_counter = 1;
    int global_counter1 = 0;
    std::thread t1([&](){
        for (int i = 0; i < 10; i++) {
            global_counter1 += 1;
        }
    });
    int global_counter2 = 0;
    std::thread t2([&](){
        for (int i = 0; i < 10; i++) {
            global_counter2 += 1;
        }
    });
    t1.join();
    t2.join();
    global_counter += global_counter1 + global_counter2;
}