使用boost::optional失败

failed attempt of using boost::optional

本文关键字:失败 optional 使用 boost      更新时间:2023-10-16

我一直在尝试使用boost可选的函数,可以返回一个对象或null,我不能弄清楚。这是我目前所知道的。对于如何解决这个问题,我将不胜感激。

class Myclass
{
public:
    int a;
};
boost::optional<Myclass> func(int a)  //This could either return MyClass or a null
{
    boost::optional<Myclass> value;
    if(a==0)
    {
        //return an object
            boost::optional<Myclass> value;
        value->a = 200;
    }
    else
    {
        return NULL;
    }
    return value;
}
int main(int argc, char **argv)
{
    boost::optional<Myclass> v = func(0);
    //How do I check if its a NULL or an object
    return 0;
}

更新:

这是我的新代码,我得到一个编译错误在value = {200};

class Myclass
{
public:
    int a;
};
boost::optional<Myclass> func(int a)
{
    boost::optional<Myclass> value;
    if(a == 0)
        value = {200};
    return value;
}
int main(int argc, char **argv)
{
    boost::optional<Myclass> v = func(0);

    if(v)
        std::cout << v -> a << std::endl;
    else
        std::cout << "Uninitilized" << std::endl;
    std::cin.get();
    return 0;
}

您的函数应该如下所示:

boost::optional<Myclass> func(int a)
{
    boost::optional<Myclass> value;
    if(a == 0)
        value = {200};
    return value;
}

你可以通过转换到bool来检查它:

boost::optional<Myclass> v = func(42);
if(v)
    std::cout << v -> a << std::endl;
else
    std::cout << "Uninitilized" << std::endl;

不应该是value->a = 200

不,不是。从Boost.Optional.Docs:

T const* optional<T (not a ref)>::operator ->() const ;
T* optional<T (not a ref)>::operator ->() ;
  • 要求:*this is initialized
  • 返回:指向所包含值的指针。
  • 抛出:没有。
  • 注意:需求是通过BOOST_ASSERT()断言的。

operator->定义中:

pointer_const_type operator->() const
{
    BOOST_ASSERT(this->is_initialized());
    return this->get_ptr_impl();
}

如果对象没有初始化,断言将失败。当我们写

value = {200};

我们用Myclass{200}初始化值。


注意,value = {200}要求支持初始化列表(c++ 11特性)。如果你的编译器不支持,你可以这样使用它:

Myclass c;
c.a = 200;
value = c;

或提供Myclass的构造函数,int作为参数:

Myclass(int a_): a(a_)
{
}

那么你可以直接写

value = 200;