0

I have class, containing a QStateMachine. It also has a couple of QState*s.

private:
QStateMachine m_machine;
QState* m_state1
QState* m_state2
...

I initialize the state machine in the constructor, and set the machine running.

As the states are private, but I want to allow a user to subclass and altering some behavior (e.g. adding transitions, change properties, connecting to signals e.t.c) I want to add some getters. I don't add setters, as the documentation states:

Removing states while the machine is running is discouraged.

The QtCreator produces something like that:

QState *MyClass:state1() const
{
    return m_state1;
}

which seems nice.

However it seems to me that this also circumvents my decision on not providing setters, as something like that is possible:

QState* state = state1();
*state = QState([...]);

which to my understanding removes the original state1 and overwrites it with a new state.

So my thought was to return a const QState* instead.

const QState* MyClass::state() const
{
    return m_state1;
}

Which seems to work (the example above will throw a compiler error). However I am that new to C++ that I am not sure that I know what I have done there and if there are other implications.

What is the right way to achieve my desired behavior?

1 Answers1

1

If you want a user to be able to retrieve the state, but be unable to affect the retrieved state object, you can consider using a constant reference return type

const QState& MyClass::state() const
{
    return *m_state1;
}

In this case, the returned object is of type const QState&, so it cannot be assigned to or be the receiver object of a non-const function call. As for the right way to achieve this behavior, returning a const QState* will result in essentially identical behavior, but require a de-reference with -> for each access.

csunday95
  • 1,279
  • 10
  • 18
  • Thank you! I think I understood a bit more, however I realized, that I can't enforce my desire, as e.g. the `QState`s `addTransition` is not const, and requires a normal pointer to another `QState`. Therefore I need to allow the non-const access to the pointer. – derM - not here for BOT dreams Aug 21 '17 at 15:18