检查变量是否已初始化

50 c++ class

看起来像这样会是重复的,但也许它是如此明显它没有被问到......

这是检查变量(非指针)是否在C++类中初始化的正确方法吗?

class MyClass
{
    void SomeMethod();

    char mCharacter;
    double mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter )
    {
        // do something with mCharacter.
    }

    if ( ! mDecimal )
    {
        // define mDecimal.
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*ler 33

无法检查变量的内容是否未定义.您可以做的最好的事情是分配一个signal/sentinel值(例如在构造函数中),以指示需要进行进一步的初始化.

  • 不幸的是,这个答案是不正确的。如果您考虑使用C ++-11,则可以在不使用哨兵值的情况下为类成员提供一个实现,请参见下面的答案。 (3认同)

lit*_*adv 21

未定义的变量将导致编译错误.

您要问的是检查它是否已初始化.但初始化只是一个值,您应该在构造函数中选择和分配.

例如:

class MyClass
{
    MyClass() : mCharacter('0'), mDecimal(-1.0){};
    void SomeMethod();

    char mCharacter;
    double mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter != '0')
    {
        // touched after the constructor
        // do something with mCharacter.
    }

    if ( mDecimal != -1.0 )
    {
        // touched after the constructor
        // define mDecimal.
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,您应该初始化为默认值,这将在逻辑上下文中表示某些内容.


Hos*_*ork 14

根据您的应用程序(特别是如果您已经使用了boost),您可能需要查看boost::optional.

(更新:从C++ 17开始,可选现在是标准库的一部分,as std::optional)

它具有您正在寻找的属性,跟踪插槽是否实际包含值.默认情况下,它构造为不保存值并计算为false,但如果计算结果为true,则允许取消引用它并获取包装值.

class MyClass
{
    void SomeMethod();

    optional<char> mCharacter;
    optional<double> mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter )
    {
        // do something with *mCharacter.
        // (note you must use the dereference operator)
    }

    if ( ! mDecimal )
    {
        // call mDecimal.reset(expression)
        // (this is how you assign an optional)
    }
}
Run Code Online (Sandbox Code Playgroud)

Boost文档中有更多示例.


Elm*_*mar 11

使用C++ 17,您可以std::optional用来检查变量是否已初始化:

#include <optional>
#include <iostream>  // needed only for std::cout

int main() {
    std::optional<int> variable;

    if (!variable) {
        std::cout << "variable is NOT initialized\n";
    }

    variable = 3;

    if (variable) {
        std::cout << "variable IS initialized and is set to " << *variable << '\n';
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这将产生输出:

variable is NOT initialized
variable IS initialized and is set to 3
Run Code Online (Sandbox Code Playgroud)

std::optional在您提供的代码中使用,您必须包含<optional>标准库头并添加std::optional<...>到相应的变量声明中:

#include <optional>

class MyClass
{
    void SomeMethod();

    std::optional<char> mCharacter;
    std::optional<double> mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter )
    {
        std::cout << *mCharacter;  // do something with mCharacter.
    }

    if ( ! mDecimal )
    {
        mDecimal = 3.14159;  // define mDecimal.
    }
}
Run Code Online (Sandbox Code Playgroud)