Search code examples
c++getternoexcept

Can getters be marked `noexcept`?


For a class such as this:

class CharMatrix
{
public:
.
.
.

private:
    int m_Y_AxisLen;
    int m_X_AxisLen;
    char m_fillCharacter;
    mutable std::vector< std::vector<char> > m_characterMatrix;
}


inline const int& CharMatrix::getY_AxisLen( ) const
{
    return m_Y_AxisLen;
}

inline const int& CharMatrix::getX_AxisLen( ) const
{
    return m_X_AxisLen;
}

inline const char& CharMatrix::getFillCharacter( ) const
{
    return m_fillCharacter;
}

inline std::vector< std::vector<char> >& CharMatrix::getCharacterMatrix( ) const
{
    return m_characterMatrix;
}

Can one mark all of these getter member functions as noexcept? Is there any chance that any of these getters might throw?

Another question is that can operator[] of std::vector throw? I checked cppreference but there was no mention of exceptions.


Solution

  • Can one mark all of these getter member functions as noexcept?
    Is there any chance that any of these getters might throw?

    You can mark them as noexcept.

    A simple return (by reference) cannot throw.
    A return by copy might throw depending of the copied type.

    can operator[] of std::vector throw?

    • For valid index, no.
    • For invalid index, your are in UB. It is not marked as noexcept to let the opportunity to "compiler" to add extra checks and possibly handle failure with exception.