【问题标题】:failed attempt of using boost::optional尝试使用 boost::optional 失败
【发布时间】:2013-06-04 02:36:48
【问题描述】:

我一直在尝试将 boost optional 用于可以返回对象或 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;
}

【问题讨论】:

    标签: c++ boost-optional


    【解决方案1】:

    您的函数应如下所示:

    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;
    

    这不是价值吗->a = 200

    不,不是。来自Boost.Optional.Docs

    T const* optional<T (not a ref)>::operator ->() const ;
    
    T* optional<T (not a ref)>::operator ->() ;
    
    • 要求:*已初始化
    • 返回:指向所包含值的指针。
    • 投掷:无。
    • 注意:需求是通过 BOOST_ASSERT() 断言的。

    operator-&gt; 定义中:

    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;
    

    【讨论】:

    • 我对@9​​87654336@ 感到困惑,它不会是value-&gt;a = 200 吗?
    • 感谢您的编辑。但是使用value = {200};,我在构建error C2143: syntax error : missing ';' before '{'时遇到编译错误@
    • 使用这段代码,你仍然会得到 /usr/include/boost/optional/optional.hpp:1117: boost::optional::pointer_type boost::optional::operator->( ) [与 T = Myclass; boost::optional::pointer_type = Myclass*]:断言 `this->is_initialized()' 失败。中止(核心转储)
    • /* 这会导致上面提到的运行时错误 / value->a = {200}; / 以下 #if 0 ,如果使用它会消除错误 */ #if 0 Myclass c; c.a = 200;值 = c; #endif
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多