简体   繁体   中英

const std::shared_ptr& const correctness

Let's say I have a class

class K
{
public:

    int k = 0;

    void Change()
    {
        k++;
    }

    void None() const
    {
        std::cout << "None \n";
    }


};

Why is it totally fine to use non const method on const reference like this?

void FN(const std::shared_ptr<K>& k)
{
    k->Change();
}

The pointer is constant not the object. You can't change which object the pointer is pointing to but you can change the object.

If you want a constant object you need:

void FN(const std::shared_ptr<const K>& k)
{
    k->Change();
}

See also: https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/ for why you might not want to use a const shared_ptr parameter at all.

Because it's the shared pointer that's const here, not the thing it points at.

If you want that to be const , you would need:

void FN(const std::shared_ptr<const K>& k)
//                            ^^^^^

As an aside, I know this is only example code but you should really make your member variable k private rather than public. Without that, users of your class don't even need the Change function, they can change it however they wish :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM