【问题标题】:How should I assign boost::interprocess::unique_ptr returned from a factory function, possibly using boost::move, in C++03我应该如何分配从工厂函数返回的 boost::interprocess::unique_ptr,可能在 C++03 中使用 boost::move
【发布时间】: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&lt;T, D&gt;::nat::*)可能由实现提供以模拟std::unique_ptr::operator=(nullptr_t),事实上它重置了unique_ptr。事实证明,这也使operator= 模棱两可。

不幸的是,使用上述static_cast&lt;&gt;() 使使用我的工厂变得过于复杂。

解决此问题的一种方法是删除 operator= 的第二个重载,因为始终可以显式调用 unique_ptr::reset()

不过,我想知道boost::move() 是否以及如何帮助我解决这个问题。

【问题讨论】:

    标签: c++ boost move unique-ptr boost-move


    【解决方案1】:

    这原来是boost::interprocess:unique_ptr 的实现中的一个错误。

    我将它报告给了库的维护者 (ticket #7598)。

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

    【讨论】:

      【解决方案2】:

      不确定它是否满足您的用例,但不是使用 unique_ptr,您不能将 my_class 设为可移动类型(使用 Boost::Move)并使用 Boost ValueFactory 作为工厂接口按值执行操作吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-05
        相关资源
        最近更新 更多