Clang: initializing a lock link from a mutex

This program is compiled by clang:

#include <mutex>

int main() {
    std::mutex mtx;
    const std::lock_guard<std::mutex>& lock(mtx);
    return 0;
}

Other major compilers refuse it (I tried gcc, msvc and icc). This is the error message from gcc:

error: invalid initialization of reference of type ‘const 
       std::lock_guard<std::mutex>&’ from expression of type ‘std::mutex’

Others give similar errors.

Is it right or wrong? Can this be reproduced with a simpler example not related to library classes? I tried, but to no avail.

Edit , this is apparently the minimum reproduction:

struct A {};

struct X
{
    explicit X(A&) {};
};

int main()
{
    A a;
    const X& x(a);
}

Interestingly, intinstead of Atriggering an error message in clang (so I could not reproduce this initially).

+6
source share
1 answer

++; CppReference on Convertting Constructors ( ):

, ( ++ 11), .

, ( , static_cast), , .

:

struct A {};

struct X
{
    explicit X(A const &) {};
};

int main()
{
    A a;
    const X& x1(A());                 // OK, direct init (no A object after init)
    const X& x3(a);                   // NOK, copy init
}
+2

All Articles