r/learncpp • u/mohammedatef555 • Sep 02 '20
Clang-Tidy: Operator=() does not handle self-assignment properly
this is my code , CLion give me this warning on operator= implementation what is wrong and why it doesn't handle it correctly
template <class Type>
class StackType
{
private:
int maxStackSize, stackTop;
Type * list;
void copyStack(const StackType<Type> &);
public:
const StackType<Type>& operator=(const StackType<Type>&);
bool isEmptyStack() const ;
bool isFullStack() const ;
void push(const Type&);
void pop();
Type top()const;
StackType(int);
StackType(const StackType<Type>&);
~StackType();
};
template <class Type>
void StackType<Type>::copyStack(const StackType<Type>& otherStack)
{
delete[]list;
maxStackSize = otherStack.maxStackSize;
stackTop = otherStack.stackTop;
list = new Type[maxStackSize];
for (int j = 0; j < stackTop; j++)
list[j] = otherStack.list[j];
}
template <class Type>
const StackType<Type>& StackType<Type>::operator=(const StackType<Type> &otherStack)
{
if (this != &otherStack)
copyStack(otherStack);
return *this;
}
3
Upvotes
View all comments
Show parent comment
2
u/PetrifiedPanda Sep 04 '20
You are absolutely right that self assignment would take way more time with this implementation. What you should consider though is that self assignment is something that is very rare, and checking for it with every assignment may not be worth it.
Keep in mind that I am unsure as well which option will be better. I just wanted to give you an alternative to your current solution.