【发布时间】:2012-10-26 11:52:33
【问题描述】:
我正在尝试创建一个返回 boost::interprocess::unique_ptr 的工厂函数。这是一个例子:
#include <boost/interprocess/smart_ptr/unique_ptr.hpp>
using namespace boost::interprocess;
class my_class {
public:
my_class() {}
};
struct my_class_deleter {
void operator()(my_class *p) {}
};
typedef unique_ptr<my_class, my_class_deleter> uptr;
uptr create() {
return uptr();
}
int main() {
uptr x;
x = create();
return 0;
}
问题是gcc无法编译上面的代码:
main.cpp:22: error: ambiguous overload for ‘operator=’ in ‘x = create()()’
../../boost_latest/boost/interprocess/smart_ptr/unique_ptr.hpp:211: note: candidates are: boost::interprocess::unique_ptr<T, D>& boost::interprocess::unique_ptr<T, D>::operator=(boost::rv<boost::interprocess::unique_ptr<T, D> >&) [with T = my_class, D = my_class_deleter]
../../boost_latest/boost/interprocess/smart_ptr/unique_ptr.hpp:249: note: boost::interprocess::unique_ptr<T, D>& boost::interprocess::unique_ptr<T, D>::operator=(int boost::interprocess::unique_ptr<T, D>::nat::*) [with T = my_class, D = my_class_deleter]
当我改变时
x = create();
到
x = boost::move(create());
然后 gcc 说:
main.cpp:22: error: invalid initialization of non-const reference of type ‘uptr&’ from a temporary of type ‘uptr’
../../boost_latest/boost/move/move.hpp:330: error: in passing argument 1 of ‘typename boost::move_detail::enable_if<boost::has_move_emulation_enabled<T>, boost::rv<T>&>::type boost::move(T&) [with T = uptr]’
我做错了吗?
有趣的是,当我这样做时:
uptr x2 = create();
代码编译没有任何问题。
顺便说一句:我使用 gcc v4.4.3 和 Boost v1.51.0。
更新:
我已经能够通过使用以下 sn-p 来克服这个问题:
x = static_cast<boost::rv<uptr>&>(create());
上述演员表基于原始问题中提到的operator= 的模糊重载的第一个版本。第二个(operator=(int boost::interprocess::unique_ptr<T, D>::nat::*)可能由实现提供以模拟std::unique_ptr::operator=(nullptr_t),事实上它重置了unique_ptr。事实证明,这也使operator= 模棱两可。
不幸的是,使用上述static_cast<>() 使使用我的工厂变得过于复杂。
解决此问题的一种方法是删除 operator= 的第二个重载,因为始终可以显式调用 unique_ptr::reset()。
不过,我想知道boost::move() 是否以及如何帮助我解决这个问题。
【问题讨论】:
标签: c++ boost move unique-ptr boost-move