Search code examples
c++design-patternsconstantsconst-cast

Design pattern for accessing non-const through a const intermediate


Can someone suggest a better design for the situation where we want two objects to "talk" to each other through a const intermediate.

Here is a contrived example, where two players trade lemons. A player finds another player in the "world", but the "world" should be const, since a player shouldn't be able to modify it (lets say by deleting walls).

void Player::give_lemon()
{
    const World& world = this->get_world();

    const Player& other = world.get_nearest_player(*this);

    this->lemons--;
    other.lemons++; // error
}

What designs do people use, a simple const_cast is easy but dirty. Or we could provide some way of "looking up" a non-const Player reference, lets say by having access to a non-const player_list() but here we'd be duplicating functionality already available in World, possibly less efficiently, all for a round-about way of doing a specific const_cast.


Solution

  • It seems that both Player and World can be seen as actors

    World happens to be const

    Introduce a Manager class that handles both:

    Manager would take a const World in its constructor and then Players can be added or removed.

    void Player::give_lemon()
    {
        Manager& mgr = this->get_manager();
    
        Player& other = mgr.get_nearest_player(*this);
    
        this->lemons--;
        other.lemons++; // error
    }
    

    The manager then keeps track of positions of players in its world. World is const and cannot have a mutable list of players, the manager can.