开发者

Strange compiler error when trying to create a temporary object

开发者 https://www.devze.com 2023-02-14 08:58 出处:网络
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!

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.

U开发者_开发问答pdate

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号