Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

c++ - Avoiding temporary when using boost::optional

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));
}

Once we have an initialized fooOpt, is there a way of assigning a new Foo to it without creating a temporary?

Something like :

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

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

boost::optional

#include <boost/optional.hpp>

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

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 (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 (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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...