gpt4 book ai didi

c++ - 使用 boost::optional 时避免临时

转载 作者:太空宇宙 更新时间:2023-11-04 12:59:20 25 4
gpt4 key购买 nike

boost::optional 支持像这样的 in_place 构造:

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

类似的东西:

fooOpt = boost::in_place<Foo>(1,3);

谢谢!

最佳答案

boost::可选

#include <boost/optional.hpp>

int main() {
boost::optional<int> x;
x = boost::in_place(3);
}

我们还可以(通过代码)显示这是通过使 Foo 继承自 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() 方法,该方法也将实现就地构造。

#include <optional>

int main() {
std::optional<int> x;
x.emplace(3);
}

boost::optional(很快...)

在版本 1.56.0 中,boost::optional 还将实现我为 std::optional 谈到的 emplace() 方法。那么,让我们看看:

#include <boost/optional.hpp>

int main() {
boost::optional<int> x;
x.emplace(3);
}

关于c++ - 使用 boost::optional 时避免临时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44989721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com