Search code examples
c++constantspass-by-reference

How do I correctly return an unmodifiable object reference from function in C++?


I am trying to return a const object from a function so that I can get information from it, but nothing can be changed once it has been created. I have the following code

    Sprite const& GetSprite() const {
        return *m_sprite;
    }


    std::unique_ptr<Sprite> m_sprite;
    int test = 5;

Somewhere else in the code I am calling this GetSprite function

Sprite sprite = entity->GetSprite();
sprite.test = 6;

This seems to compile fine and after stepping through the value in test is actually changed. I would have assumed that the object returned from GetSprite would not allow me to modify the object, but the const qualifier seems to be dropped?

Am I doing this wrong or is there a different approach to achieve this?


Solution

  • Sprite sprite = entity->GetSprite();
    

    this creates a copy of the Sprite object GetSprite returns, using the copy-consturctor of `Sprite.

    Editing the copy should not cause the original to be modified, unless you have written Sprite wrong, or you get confused between reference, value and pointer semantics.

    Sprite const& sprite = entity->GetSprite();
    

    this gets a reference to the contained Sprite through which you cannot modify it.

    If you want to block copying of Sprites, you can do:

    Sprite(Sprite const&) = delete;
    

    but I'd advise allowing moving of Sprites:

    Sprite(Sprite&&) = default;
    

    especially pre- (when guaranteed elision makes it less important).