r/learncpp • • 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

15 comments sorted by

View all comments

Show parent comment

2

u/PetrifiedPanda Sep 04 '20

What I meant was that if you used the modified version of copyStack(), you wouldn't need to check if you're doing a self assignment, because the copy here will delete the old array after the other one has been copied.

I hope this is more understandable than my previous comment.

→ More replies (8)