【问题标题】:Passing a member function to std::thread without address-of在没有地址的情况下将成员函数传递给 std::thread
【发布时间】:2016-02-18 22:34:39
【问题描述】:

我有以下代码,它可以与 GCC 4.8.4、GCC 5.2.0 和 clang 3.8.0 主干(使用 -std=c++11)愉快地编译

#include <utility>
#include <thread>

struct Callable {
    static void run() {}
};

void start(Callable && c)
{
    std::thread t(&c.run); // construct thread
}

int main()
{
    Callable c;
    start(std::move(c));
}

(在左值上使用 std::move 是不合理的,但这不是重点)。

但是,如果我将线程构造函数调用更改为

std::thread t(c.run);

clang 仍然编译它,但 GCC 5.2.0 抱怨:

/home/bulletmagnet/workspace/zarquon/prog/msyncd/src/new_thread_test.cc: In function ‘void start(Callable&&)’:
/home/bulletmagnet/workspace/zarquon/prog/msyncd/src/new_thread_test.cc:10:24: error: no matching function for call to ‘std::thread::thread(void())’
     std::thread t(c.run);
                        ^
In file included from /home/bulletmagnet/workspace/zarquon/prog/msyncd/src/new_thread_test.cc:2:0:
/usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/include/c++/thread:133:7: note: candidate: std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void(); _Args = {}]
       thread(_Callable&& __f, _Args&&... __args)
       ^
/usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/include/c++/thread:133:7: note:   no known conversion for argument 1 from ‘void()’ to ‘void (&&)()’
/usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/include/c++/thread:128:5: note: candidate: std::thread::thread(std::thread&&)
     thread(thread&& __t) noexcept
     ^
/usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/include/c++/thread:128:5: note:   no known conversion for argument 1 from ‘void()’ to ‘std::thread&&’
/usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/include/c++/thread:122:5: note: candidate: std::thread::thread()
     thread() noexcept = default;
     ^
/usr/local/lib/gcc/x86_64-unknown-linux-gnu/5.2.0/include/c++/thread:122:5: note:   candidate expects 0 arguments, 1 provided

(GCC 4.8.4 也抱怨)。

那么,哪个编译器是正确的?

【问题讨论】:

    标签: c++ c++11 g++ clang++


    【解决方案1】:

    认为 Clang 是对的,EDG 也接受代码,所以我打开了https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68386

    显而易见的解决方法是不要使用那种奇怪的语法来引用静态成员函数,而是将其称为 Callable::run,无论是否使用 &amp; 运算符都可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 2015-04-12
      • 2021-09-04
      • 2021-05-30
      • 1970-01-01
      • 2017-03-22
      • 2014-02-20
      相关资源
      最近更新 更多