Check for value definedness in C++

2020-04-05 12:09发布

I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}

Is it possible in C++?

Thanks

标签: c++ undef
9条回答
放我归山
2楼-- · 2020-04-05 12:20

Why not maintain a separate flag that gets initialized to false and then gets set to true when bar is calculated. It can then be 'undefed' by setting the flag to false again.

if(!isBarValid)
{
    calculateBar();
    isBarValid = true;
}
return bar;
查看更多
倾城 Initia
3楼-- · 2020-04-05 12:21

If you mean at run-time, there is no such thing. If bar is never initialized, it will have whatever random bits happen to be there, depending on how the object is allocated (some allocators will initialize new memory to all-zero).

edit: it's up to the programmer to handle object state in constructors and/or manual initialization methods like init()

查看更多
手持菜刀,她持情操
4楼-- · 2020-04-05 12:25

As others pointed out, there is nothing like an "undefined" state. But you may want to look into boost.optional

查看更多
beautiful°
5楼-- · 2020-04-05 12:26

C++ does not have an "undefined" state for primitive types. The closest available for float/double would be NAN, but that really has a different meaning.

查看更多
疯言疯语
6楼-- · 2020-04-05 12:27

This is not possible in C/C++, primitives will always a value assigned (mostly garbage, whatever was on that spot in memory before it, unless explicitly assigned at declaration). I's common to have a placeholder value (i.e. 0 for pointers) which denotes not-used, however these have to be explicitly assigned as well. If your double can take on any value, then I suggest you put a boolean next to it, assigned to false initially, and test/set that one when you want to do your calculation.

查看更多
我欲成王,谁敢阻挡
7楼-- · 2020-04-05 12:31

Initialize bar to some value which can never occur when you call the something() function in the constructor.

For example:

Foo(): bar(-1)
{
}

Then check for the value -1 in the get_bar function.

(hmmm Laserallan also posted that answer 1 minute before :-( ;-) )

查看更多
登录 后发表回答