C & C++

C & C++

By DeepSource

Found reference data members CXX-W2012

Anti-pattern

Reference data members are generally risky to use as they may be pointing to dangling memory blocks. Having such members is rarely useful, and makes the class only copy-constructible but not copy-assignable.

If it was intended to be a referential value consider using a smart pointer.

Bad practice

class Foo {
private:
    int& bar;
public:
    Foo(int i): bar(i) {}
}

Recommended

class Foo {
private:
    std::unique_ptr<int> bar;
public:
    Foo(int i) {
        bar = std::make_unique<int>(i);
    }
}