c++classvariablesif-statement

Declaring class variable inside an if statement


c++ accepts:

if(int a=1)
{
    //...
}

For learning purposes, I have written a simple lock mechanism class:

class SimpleLock
{
public:
    class Token
    {
    public:
        friend class SimpleLock;
        Token(SimpleLock & lock) : lock(lock), locked(!lock.locked.exchange(true)) { }
        ~Token() { if(locked) lock.locked.store(false); }
        operator bool() const { return locked; }

    private:
        SimpleLock & lock;
        const bool locked;
    };

    SimpleLock() : locked(false) { }

private:
    std::atomic_bool locked;
};

allowing me to do:

SimpleLock::Token t(lock);

if(t) //Token has an operator bool() overload
{
    //...
}

Why doesn't the following compile?

if(SimpleLock::Token t(lock))
{
    //...
}

Compiler error:

expected primary-expression before 't'

Online code link


Solution

  • It doesn't compile because that form of initialization is not allowed in an if condition. This is just down to the syntactic forms which the standard says are valid.

    You can either use the copy-initialization form or a braced-init-list:

    if(SimpleLock::Token t = SimpleLock::Token(lock))
    {
        //...
    }
    
    if(SimpleLock::Token t{lock})
    {
        //...
    }
    

    This is specified in [stmt.select]/1 (N3337):

    condition:

    • expression

    • attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause

    • attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list