gpt4 book ai didi

c++ - clang:从互斥锁初始化锁引用

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:42:35 24 4
gpt4 key购买 nike

这个程序是clang编译的:

#include <mutex>

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

其他主要编译器拒绝它(我已经尝试过 gcc、msvc 和 icc)。这是来自 gcc 的错误消息:

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

其他人给出了类似的错误。

clang是对还是错?这可以用一个不涉及库类的更简单的例子来重现吗?我试过了,但没有用。

编辑这似乎是最小的复制:

struct A {};

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

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

有趣的是,用 int 代替 A 确实会触发 clang 中的错误消息(这就是我最初无法重现的原因)。

最佳答案

我没有C++标准的相关章节;我只能引用CppReference on Converting Constructors现在(强调我的):

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.

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.

所以:

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
}

关于c++ - clang:从互斥锁初始化锁引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47264618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com