只是一点例子,没有什么解释;主要是给自己看,作为一个笔记而已。
boost::optional例子:
#include <boost/optional.hpp>
#include <iostream>
class Inner
{
private:
int v;
public:
Inner(int _v) : v(_v)
{}
Inner(const Inner& other) : v(other.v)
{
std::cout << "Inner(const Inner& other)" << std::endl;
}
Inner& operator=(const Inner& other)
{
this->v = other.v;
std::cout << "Inner& operator=(const Inner& other)" << std::endl;
return *this;
}
bool operator==(const Inner& other)
{
std::cout << "bool operator==(const Inner& other)" << std::endl;
return this->v == other.v;
}
friend std::ostream& operator<<(std::ostream& out, const Inner& inner)
{
out<<"Inner("<<inner.v<<")";
return out;
}
int get_v()
{
return v;
}
void set_v(int _v)
{
v = _v;
}
};
int main()
{
boost::optional<Inner> option1;
assert(!option1);
boost::optional<Inner> option2(boost::none);
assert(!option2);
Inner inner3(3);
//the following two statements are equal to each other;
boost::optional<Inner> option3(inner3); // output: Inner(const Inner& other) -- copy the object;
boost::optional<Inner> option4 = inner3; // output: Inner(const Inner& other) -- copy the object;
assert(*option3 == *option4); // output: bool operator==(const Inner& other) -- behaves like a pointer;
//optional behaves like a pointer, but it holds a copy of the object instead of the pointer of the object;
std::cout << "option3 = " << option3->get_v() << std::endl; // output: option3 = 3
option3->set_v(8);
std::cout << "option3 = " << option3->get_v() << std::endl; // output: option3 = 8
std::cout << "inner3 = " << inner3.get_v() << std::endl; // output: inner3 = 3
boost::optional<Inner> option5;
option5 = option4; // output: Inner(const Inner& other) -- make a copy (copy constructor)
std::cout << "option4 = " << option4->get_v() << std::endl; // output: option4 = 3
std::cout << "option5 = " << option5->get_v() << std::endl; // output: option5 =