C ++ Strange behavior when comparing strings

I use cpp.sh to compile and run this code. I expect the numberdefault value to be initialized with a value 0or some garbage value. However, in the constructor, although the condition ifis false, the value numberis still initialized with the value 10. Can someone explain to me what is going on?

#include <iostream>

class Number
{
    int number;
public:
    Number(std::string s)
    {
        if (s == "foo")
        {
            number = 10;
        }
    }
    int getNumber()
    {
        return number;
    }
};

int main()
{
  Number n("bar");
  std::cout << n.getNumber() << std::endl;
}
+6
source share
5 answers

From clause 9 in [dcl.decl]

, . , , , ,

10 , , .

+11

. int . {}. , . -

class Number
{
    int number {0}; // or any other default value.
};

, Undefined . Undefined - http://en.cppreference.com/w/cpp/language/ub

+4

. .

number , UB. (cpp.sh, ) Full (-O2), 10, , .

normal, .

VS 2017, , .

, . , , cpp.sh Full (-o2)

+4

, undefined , 10 ( !). UB .

, . :

Number(std::string s)
    : number ( -1 )
{
    if (s == "foo")
    {
        number = 10;
    }
}
+3

, s "foo", Number. , n.getNumber(), undefined bahavior. , , , ( 10, ).

+2
source

All Articles