Return & const or * const? (C ++)

I have my own SomeObject class with multiple members.

I now have another "WorkingClass" class that binds this object as a private member.

My question is: I want to create a Getter for "SomeObject", but I do not want anyone to modify it.

which way is better, 1 or 2?

class WorkingClass
{
private:
    SomeObject sObj;

public:
    //... 1)
    const SomeObject &const GetSomeObject()
    {
        return mousePosition;
    }

    //... 2)
    const SomeObject *const GetSomeObject()
    {
        return &mouseMovement;
    }
}

I know you can always drop const, but still I'm just trying to make my code clean and reliable

EDIT:

then I have one more question. when I have a smart-pointer element and use it a lot inside the class, and then suddenly want someone to have access to read some values, but no more, is this a good solution or is it verbose again?

class X
{
private:
    boost::shared_ptr<SomeObject> sob

public:
    const const & GetSomeObject()
    {
        return *sob.get();
    }
}

"const boost:: shared_ptr <... > GetX()"? , , GetX(). reset (..) , const boost::... . ?

+5
2

:

  • const SomeObject &const . const- . ( , , .)

  • const SomeObject *const . o.GetSomeObject() rvalue, r- const-qual. const SomeObject*. (const SomeObject *const , .)

, , , . . , const, const const:

const SomeObject& GetSomeObject() { ... }
const SomeObject* GetSomeObject() { ... }

.

+7

& const . . const.

, . , .

. ?

, , , .

, , " ". , . , - .

, "" - , . , / NULL ( , NULL ).

+5

All Articles