Strange compiler error when trying to create a temporary object

252 views Asked by At

After I posting this question I tried to reproduce the problem of accidental rvalue creation when creating a scoped RAII object. Now it appears that I can't reproduce it without compiler errors!

In the following code sample, in Test::foo() the second ScopedLock creation doesn't compile. The gcc compiler error seems totally wrong. Can anyone explain?

struct Mutex
{
    void lock() { }

    void unlock() { }
};


struct ScopedLock
{
    ScopedLock(Mutex & inMutex) : mMutex(inMutex)
    { mMutex.lock(); }

    ~ScopedLock()
    { mMutex.unlock(); }

private:
    ScopedLock(const ScopedLock&);
    ScopedLock& operator=(const ScopedLock&);

    Mutex mMutex;
};


struct Test
{
    void foo()
    {
        // Compiles fine
        ScopedLock lock(mMutex);

        // Error: no matching function for
        // call to ‘ScopedLock::ScopedLock()’
        ScopedLock(mMutex);
    }

    Mutex mMutex;
};

I'm using GCC 4.2.1 on Mac.

Update

I had a look at the original code and saw that the member was referenced through the this pointer:

ScopedLock(this->mMutex); // short-lived temporary and compiles fine
2

There are 2 answers

0
AProgrammer On BEST ANSWER

You have two user declared constructors, so there is no compiler generated default one.

Yes,

Type (i);

is handled in the same way as

Type i;

Such parenthesis are useful in more complex declarations such as

Type (*i)();

to declare a pointer to a function returning a type.

4
ceo On

The message is telling you that ScopedLock doesn't have a default constructor, i.e. one that takes no arguments. If you declare a constructor that takes arguments, C++ won't create a default one for you.