init boost ::可选的非复制对象 [英] init boost::optional of non-copyable object

查看:102
本文介绍了init boost ::可选的非复制对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果基础类型T是不可默认构造的,不可复制/可移动的,但实例仍然可以存在,该怎么做初始化boost::optional< T >?

What should I do to initialize boost::optional< T > if underlying type T is non-default constructible, non-copyable/moveable, but one's instance still can exist?

出于任何语义原因而禁止boost::optional具有某些成员函数(如template< typename... Args > boost::optional< T >::construct(Args && ...args)),该成员函数将所有参数传递到就地operator new中以完全构造对象(对于非引用类型T )?变体是具有非成员功能,例如std::make_shared< T >.

Is it forbidden for boost::optional by any semantic reasons to have some member function like template< typename... Args > boost::optional< T >::construct(Args && ...args), that delivers all the arguments to in-place operator new to construct the object entirely (for non-ref type T)? Variant is to have non-member function like std::make_shared< T >.

在我看来,可以通过使用std::unique_ptr/std::shared_ptr来解决我的问题,但是在这种情况下,我的问题是:为什么boost::optional进度被冻结?".

It seems to me, that my problem can be solved by means of using of std::unique_ptr/std::shared_ptr, but in this case my question is: "Why boost::optional progress is frozen?".

推荐答案

boost::optional可以使用具体来说,您可以像这样使用它们:

Specifically, you can use them like this:

#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>

class MyType : private boost::noncopyable
{ 
public:
  MyType(T1 const& arg1, T2 const& arg2);
}
...
boost::optional<MyType> m_var;
...
m_var = boost::in_place(arg1, arg2);
...

在C ++ 14中,有一个建议的 std::make_optional 解决这个问题.但是,Boost.Optional中尚未实现此功能.

In C++14 there is a proposed std::make_optional that would be a better solution to this problem. However, this has not been implemented in Boost.Optional.

这篇关于init boost ::可选的非复制对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆