【发布时间】:2015-08-15 17:29:05
【问题描述】:
编辑:最后添加了编译器错误。 首先,我要说我已经设置并运行了 Visual Studio Express 2013 和 CodeBlocks (Mingw w64)。 但是我在使用一个编译器而不是另一个编译器编译某些代码时遇到问题,反之亦然。
考虑这段代码:
void foo(std::string& s){
std::cout << "in foo function now" << std::endl;
s = "the new string.";
}
int main(){
std::string s = "the original string";
std::thread t1(foo, std::ref(s));
t1.join();
if (!s.size()) std::cout << "s is empty" << std::endl;
else std::cout << s << std::endl;
std::cin.get();
return 0;
}
它在 GCC 和 VS 上都能正常编译和运行。
但是,如果我决定将 std::ref(s) 更改为 std::move(s),它将不再使用 GCC 编译,但可以使用 VS。
要修复它,我必须添加一个 '&' 使 void foo(std::string& s) 变为 void foo(std::string&& s),然后它将使用 gcc 编译,但不再使用 VS!
我的猜测是 VS 编译器是安静宽容的,并且没有严格遵守标准,但我没有使用 std::function 和 std::bind 的这种行为,即使参数传递相同我相信的方式。
无论如何,我非常感谢能帮助我了解正在发生的事情。
编辑:错误: 海湾合作委员会:
C:/mingw-w64/x86_64-5.1.0-posix-seh-rt_v4-rev0/mingw64/x86_64-w64-mingw32/include/c++/functional:1505:61: error: no type named 'type' in 'class std::result_of<void (*(std::__cxx11::basic_string<char>))(std::__cxx11::basic_string<char>&)>'
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
C:/mingw-w64/x86_64-5.1.0-posix-seh-rt_v4-rev0/mingw64/x86_64-w64-mingw32/include/c++/functional:1526:9: error: no type named 'type' in 'class std::result_of<void (*(std::__cxx11::basic_string<char>))(std::__cxx11::basic_string<char>&)>'
_M_invoke(_Index_tuple<_Indices...>)
VS 一:
Error 1 error C2664: 'void (std::string &&)' : cannot convert argument 1 from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'std::string &&' c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional 1149 1 Tests
【问题讨论】:
-
明确引用编译器错误。可能相关:std::thread constructor doesn't handle movable object
-
foo(std::move(s))也不应该编译。可变引用不会绑定到右值表达式。所以std::move将参数放入std::thread构造函数中预计不会起作用。
标签: c++ c++11 gcc visual-studio-2013 stdthread