为什么将boost::move()的返回值分配给非常数引用在C++0x模式下失败,但在C++03模式下有效



以下是可用于重现问题的源代码:

#include <iostream>
#include <boost/bind.hpp>
#include <boost/move/move.hpp>
#include <boost/ref.hpp>
std::ostream& dump_to_stream(std::ostream& os, int a, int b) {
return os << a << 'n' << b << 'n';
}
template <class R, class F>
R call_under_lock(F f) {
// lock();
R r = f();
// unlock();
return boost::move(r);
}
int main() {
std::ostream& os = call_under_lock<std::ostream&>(
boost::bind(&dump_to_stream, boost::ref(std::cout), 1, 2));
}

当在GCC中使用C++03模式时,代码编译没有任何问题。另一方面,使用C++0x模式会产生以下错误:

$ g++ -I../../boost_latest -std=c++0x -O2 -Wall -Wextra   -c -o test.o test.cpp
(...)
test.cpp: In function ‘R call_under_lock(F) [with R = std::basic_ostream<char>&, F = boost::_bi::bind_t<std::basic_ostream<char>&, std::basic_ostream<char>& (*)(std::basic_ostream<char>&, int, int), boost::_bi::list3<boost::reference_wrapper<std::basic_ostream<char> >, boost::_bi::value<int>, boost::_bi::value<int> > >]’:
test.cpp:20:62:   instantiated from here
test.cpp:15:23: error: invalid initialization of non-const reference of type ‘std::basic_ostream<char>&’ from an rvalue of type ‘boost::remove_reference<std::basic_ostream<char>&>::type {aka std::basic_ostream<char>}’
(...)

失败的原因是什么?有没有办法在C++11模式下解决它?

上面给出的代码简化了我在通用代码中使用的内容。因此需要这样的组合(boost::move+作为返回值类型的非常数ref)。

我使用的是gcc v4.6.3、Boost 1.54.0和Ubuntu 12.04(i386)。

更新1:我使测试用例更加真实。目标是有一个泛型函数,它调用锁下的函子,并通过boost::move()返回函子返回的值,因为返回值的类型可能是可移动的,但不可复制(在我对call_under_lock()的一些调用中也是如此)。

更新2:当在C++11模式中使用clang 3.5.1~(exp)时,可以观察到类似的问题:

$ clang test.cpp -I../../boost_latest/ -lstdc++ --std=c++11
test.cpp:11:10: error: non-const lvalue reference to type 'basic_ostream<[2 * ...]>' cannot bind to a temporary of type 'basic_ostream<[2 * ...]>'
return boost::move(r);
^~~~~~~~~~~~~~
test.cpp:19:22: note: in instantiation of function template specialization 'call_under_lock<std::basic_ostream<char> &, boost::_bi::bind_t<std::basic_ostream<char> &, std::basic_ostream<char> &(*)(std::basic_ostream<char> &, int, int),
boost::_bi::list3<boost::reference_wrapper<std::basic_ostream<char> >, boost::_bi::value<int>, boost::_bi::value<int> > > >' requested here
std::ostream& os = call_under_lock<std::ostream&>(

更新3:boost用户邮件列表[1]中也讨论过这个话题。

[1]http://boost.2283326.n4.nabble.com/move-differences-between-results-in-C-03-and-C-11-modes-td4659264.html

发生这种故障的原因是什么?

在C++03中,R是std::ostream&,而boost::move()显然返回相同的类型,因此没有问题。

在C++11中,R仍然是std::ostream&,但是boost::move()将返回std::ostream&&。这使得表达式boost::move()成为一个右值,它不能绑定到非常量左值引用。

有办法在C++11模式下解决它吗?

是:

template <class R, class F>
R call_under_lock(F f) {
// lock();
R r = f();
// unlock();
return r;
}

在C++03和C++11中,这应该完全符合您的要求。它会在你想要的时候移动,而不是在你不想要的时候。

最新更新