Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Warning for "anonymous" variable creation in c++

Tags:

c++

gcc

I've a class like this:

class ScopedLock {
public:
    ScopedLock (Locker *lock) { /*...*/ }
    ~ScopedLock () { /*...*/ }
};

Normally it's called like (this will call the constructor/destructor of ScopedLock at the correct place) :

{
    ScopedLock l(&locker);
    // ...
}

I've accidentally called it like:

{
    ScopedLock(&locker);
    // ...
}

What is the name for such a "thing"? Unused anonymous local variable?

Is there a possibility to prevent this? Is there a compiler warning available for such a "thing"?

like image 627
powerpete Avatar asked Mar 05 '23 20:03

powerpete


2 Answers

You have created an unnamed temporary / nameless temporary object of type ScopedLock that lives briefly and then dies at the ;. The compiler does not issue a warning as it assumes you are doing something useful with it. It does not go into a ctor body to inspect if that might be the case. For example you want to create a temporary where your constructor might do some work:

ScopedLock() {
    // do some work
}

You can't force a compiler to show a warning for such use-cases and there is no such flag in GCC.

The following SO posts can prove beneficial:

like image 163
Ron Avatar answered Mar 28 '23 04:03

Ron


You can make a construction function marked as nodiscard that should be invoked instead of constructor.

#include <iostream>

class ScopedLock final
{
    private: ScopedLock(int, int) {std::cout << "constructed" << std::endl;}
    private: ScopedLock(void)                            = delete;
    private: ScopedLock(ScopedLock const &)              = delete;
    private: ScopedLock(ScopedLock &&)                   = delete;
    private: ScopedLock & operator =(ScopedLock const &) = delete;
    private: ScopedLock & operator =(ScopedLock &&)      = delete;

    public: [[nodiscard]] static ScopedLock
    construct(int x, int y)
    {
        return ScopedLock{x, y};   
    }
};

int main()
{
    ScopedLock(12, 123); // Error
    ScopedLock::construct(12, 123); // Warning
    auto lock(ScopedLock::construct(12, 123)); // Ok
}

online compiler

like image 22
user7860670 Avatar answered Mar 28 '23 03:03

user7860670