'QAC Warning regarding destructor
I have a class defined like somewhat below where copy constructor and assignment operator are deleted. QAC is throwing a warning that "This class has declared default or deleted special members but no destructor". Why is the warning and how to I solve it?
class A
{
public:
static A& getInstance()
{
static A AInstance;
return AInstance;
}
A(A const&) = delete;
void operator=(A const&) = delete;
private:
A();
};
Solution 1:[1]
The linker warning shows what is wrong:
In function
A::getInstance()': <source>:8: undefined reference toA::A()'
The fix is simple:
class A
{
public:
static A& getInstance()
{
static A AInstance;
return AInstance;
}
A(A const&) = delete;
A& operator=(A const&) = delete; //< fix 2
private:
A() = default; //< fix 1 (C++11)
};
Fix 1: Provide the definition (let the compiler do it by using "=default" or use {} for old C++)
Fix 2: see https://en.cppreference.com/w/cpp/language/copy_assignment
Fix 3: (if you want to make it explicit) also delete the move constructor and the move assignment operator.
Notes:
- Be careful when you use singletons / variables with static storage duration: specifically when it is possible that a destructor of another object might use the singleton. The C++ FAQ explains why: https://isocpp.org/wiki/faq/ctors#construct-on-first-use-v2 (Static Deinitialization Order Fiasco).
- As the question is about QAC and static code analysis: have also a look at
- https://wiki.sei.cmu.edu/confluence/display/cplusplus/DCL56-CPP.+Avoid+cycles+during+initialization+of+static+objects and
- https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#i3-avoid-singletons
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sonic78 |
