C++ defining a constant member variable inside class constructor

前端 未结 4 979
猫巷女王i
猫巷女王i 2021-02-05 10:35

Usually when you have a constant private member variable in your class, which only has a getter but no setter, it would look something like this:

// Example.h
cl         


        
4条回答
  •  無奈伤痛
    2021-02-05 10:56

    This answer addresses a problem with all of the other answers:

    This suggestion is bad:

    m_value(myVec.size() ? myVec.size() + 1 : -1)
    

    The conditional operator brings its second and third operand to a common type, regardless of the ultimate selection.

    In this case the common type of size_t and int is size_t. So if the vector is empty, the value (size_t)-1 is assigned to the int m_value, which is an out-of-range conversion, invoking implementation-defined behaviour.


    To avoid relying on implementation-defined behaviour the code could be:

    m_value(myVec.size() ? (int)myVec.size() + 1 : -1)
    

    Now, this retains another problem that the original code had: out of range conversion when myVec.size() >= INT_MAX. In robust code this problem should also be addressed.

    I would personally prefer the suggestion to add a helper function, which performs this range test and throws an exception if the value is out of range. The one-liner is possible although the code is starting to get hard to read:

    m_value( (myVec.empty() || myVec.size() >= INT_MAX) ? -1 : (int)myVec.size() + 1 )
    

    Of course there are a few other ways to deal with this problem more cleanly, e.g. use size_t for m_value and either have (size_t)-1 as the sentinel value, or preferably avoid the need for a sentinel value entirely.

提交回复
热议问题