开发者

bool pointer member behaviour different on assigning true vs false

开发者 https://www.devze.com 2023-02-11 00:38 出处:网络
i use simple bool pointer class member. Assigning false resp. true behaves different - see comments in code.

i use simple bool pointer class member. Assigning false resp. true behaves different - see comments in code. I ou开发者_如何学Gotcomment one to test the other below.

I use compiler call g++ -o basic basic.cpp

class Test
{
public:
    int a;
    bool* abool;
};


int main() {
    Test t;

    //t.abool = false;              // WORKS
    //t.abool = true;               // ERROR: cannot convert 'bool' to 'bool*' in assignment - expected IMO; 

    // this should work for both values IMO
    //*(t.abool) = true;            // Segmentation fault
    //*(t.abool) = false;           // Segmentation fault



    cout << t.abool << endl;

    return 0;
}


That is because a conversion exists from false to 0. So it becomes t.abool = 0; which is initializing abool with NULL. However, true converts to 1 and since you can't initialize the pointer with an absolute integer, you get a compiler error. In the second case (with comment this should work IMO) you will get a seg fault as you are trying to dereference an unitialized pointer which invokes undefined behavior.


You're bool* hasn't been initialized to point to anything.

You can assign it a null pointer value (which false will convert to), or a valid pointer to a bool object:

bool test;

t.abool = 0; // or NULL
t.abool = &test;

Once it's pointing at an actual bool object you can assign bool value to that object through the pointer:

*t.abool = true;
*t.abool = false;


false works because false is probably seen as 0 by g++


Any literal of numeric type and value zero can be implicitly converted to a null pointer. bool is a numeric type, and false has value zero. Non-zero values (such as true) can't be implicitly converted to a pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消