2012-10-26 24 views
3

我想创建一个工厂函数,将返回boost :: interprocess ::的unique_ptr。这里有一个例子:我应该如何分配boost :: interprocess :: unique_ptr从工厂函数返回,可能使用boost :: move,在C + + 03

#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。


UPDATE:

我已经能够通过使用下面的代码片断来解决这个问题:

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()是否以及如何帮助我解决这个问题。

回答

3

原来这是执行boost::interprocess:unique_ptr时的一个错误。

我向图书馆的维护人员报告(ticket #7598)。

该错误已得到修复,修复将在Boost v1.54.0中提供。

0

不确定它是否符合你的用例,而不是使用unique_ptr,你不能让my_class成为一个可移动的类型(使用Boost :: Move)并且使用工厂接口的Boost ValueFactory通过值做事情吗?

相关问题