Strange compiler error when trying to create a temporary object

倾然丶 夕夏残阳落幕 提交于 2019-12-12 15:40:16

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5159438/strange-compiler-error-when-trying-to-create-a-temporary-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!