Is it possible to set an object to null?

前端 未结 5 1894
一个人的身影
一个人的身影 2020-12-01 07:39

Further in my code, I check to see check if an object is null/empty.

Is there a way to set an object to null?

5条回答
  •  渐次进展
    2020-12-01 07:55

    While it is true that an object cannot be "empty/null" in C++, in C++17, we got std::optional to express that intent.

    Example use:

    std::optional v1;      // "empty" int
    std::optional v2(3);   // Not empty, "contains a 3"
    

    You can then check if the optional contains a value with

    v1.has_value(); // false
    

    or

    if(v2) {
        // You get here if v2 is not empty
    }
    

    A plain int (or any type), however, can never be "null" or "empty" (by your definition of those words) in any useful sense. Think of std::optional as a container in this regard.

    If you don't have a C++17 compliant compiler at hand, you can use boost.optional instead. Some pre-C++17 compilers also offer std::experimental::optional, which will behave at least close to the actual std::optional afaik. Check your compiler's manual for details.

提交回复
热议问题