问题描述
boost ::可选支持in_place构造,如下所示:
boost::optional support in_place construction like so:
#include <boost/optional.hpp>
#include <boost/utility/typed_in_place_factory.hpp>
class Foo
{
int a,b;
public:
Foo(int one, int two) : a(one),b(two) {}
};
int main()
{
boost::optional<Foo> fooOpt(boost::in_place<Foo>(1,3));
}
一旦有了初始化的fooOpt,是否可以在不创建临时Foo的情况下为其分配新的Foo?
Once we have an initialized fooOpt, is there a way of assigning a new Foo to it without creating a temporary?
类似的东西:
fooOpt = boost::in_place<Foo>(1,3);
谢谢!
推荐答案
boost :: optional
#include <boost/optional.hpp>
int main() {
boost::optional<int> x;
x = boost::in_place(3);
}
我们还可以通过使Foo
从boost::noncopyable
继承来显示(通过代码)这是就地构建对象:
We can also show (via code) that this is building the object in-place by making Foo
inherit from boost::noncopyable
:
#include <boost/optional.hpp>
#include <boost/noncopyable.hpp>
class Foo : boost::noncopyable {
public:
Foo(int one, int two) {}
};
int main() {
boost::optional<Foo> x;
x = boost::in_place(3, 4);
}
std :: optional(最终...)
最终,我们将可以访问std::optional
.此类型将实现emplace()
方法,该方法还将实现就地构造.
std::optional (eventually...)
Eventually, we will get access to std::optional
. This type will implement an emplace()
method, that will implement in-place construction as well.
#include <optional>
int main() {
std::optional<int> x;
x.emplace(3);
}
boost :: optional(很快...)
在版本1.56.0中,boost::optional
还将实现我在std :: optional中讨论的emplace()
方法.因此,让我们来看一下:
boost::optional (soon...)
In version 1.56.0, boost::optional
will also implement the emplace()
method that I talked about for std::optional. So, let's see that:
#include <boost/optional.hpp>
int main() {
boost::optional<int> x;
x.emplace(3);
}
这篇关于使用boost :: optional时避免临时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!