C & C++

C & C++

Made by DeepSource

Implicit deletion of copy and move assignment constructors due to non-static const data member CXX-W2010

Anti-pattern
Minor

Const or reference data members are only allowed to be initialized by the constructor of the class, and never after. And unlike in other languages, they are still instance dependent types. Having such members is rarely useful, and makes the class only copy-constructible but not copy-assignable.

That is to say, const data members will result in implicit deletion of copy and move assignment constructors.

If it was intended to be a constant value attached to the class or struct type itself consider using a static const member.

Bad practice

class Foo {
private:
    const int bar;
    int& ref_mem;
public:
    Foo(int& ref_param): bar(10), ref_mem(ref_param)  {}
};

Recommended

class Foo {
private:
    static const int bar = 10;
    std::unique_ptr<int> mem;
public:
    Foo(int param) {
      bar = std::make_unique<int>(param);
    }
};