简体   繁体   English

铛:从互斥锁初始化锁引用

[英]clang: initialising a lock reference from a mutex

This program is compiled by clang: 该程序由clang编译:

#include <mutex>

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

Other major compilers refuse it (I have tried gcc, msvc, and icc). 其他主要的编译器拒绝它(我尝试过gcc,msvc和icc)。 This is an error message from gcc: 这是来自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 clang right or wrong? lang是对是错? Can this be reproduced with a simpler example not involving library classes? 可以用一个不涉及库类的简单示例来重现吗? I have tried but to no avail. 我已经尝试过,但没有成功。

Edit this seems to be the minimal reproduction: 编辑这似乎是最小的复制:

struct A {};

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

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

Interestingly, an int in place of A does trigger the error message in clang (which is why I could not reproduce this initially). 有趣的是,代替Aint确实触发了clang错误消息(这就是为什么我最初无法重现此错误的原因)。

I don't have the relevant chapter and verse of the C++ standard; 我没有C ++标准的相关章节。 I can only refer to CppReference on Converting Constructors right now (emphasis mine): 我现在只能参考有关转换构造函数的CppReference (重点是我的):

A constructor that is not declared with the specifier explicit and which can be called with a single parameter (until C++11) is called a converting constructor . 使用说明符进行显式声明的构造函数,并且可以使用单个参数(直到C ++ 11)调用该构造函数,构造函数称为“ 转换构造函数”

Unlike explicit constructors, which are only considered during direct initialization (which includes explicit conversions such as static_cast), converting constructors are also considered during copy initialization, as part of user-defined conversion sequence. 仅在直接初始化 (包括显式转换,例如static_cast)中考虑的显式构造函数不同 ,在拷贝初始化期间,转换的构造函数也作为用户定义的转换序列的一部分被考虑。

So: 所以:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM