简体   繁体   中英

Unique pointer and const correctness

I was not expecting this code to compile:

#include <iostream>
#include <memory>

class A
{
public:

    inline int get() const
    {
        return m_i;
    }

    inline void set(const int & i)
    {
        m_i = i;
    }

private:

    int m_i;
};

int main()
{
    const auto ptr = std::make_unique< A >();

    ptr->set( 666 ); // I do not like this line    D:<
    std::cout << ptr->get( ) << std::endl;

    return 0;
}

If ptr was a raw C pointer, I would be ok with that. But since I'm using a smart pointer , I can't understand what is the rationale behind this.

I use the unique pointer to express ownership , in Object Oriented Programming this could be seen as an object composition ("part-of" relationship).

For example:

class Car
{
    /** Engine built through some creational OO Pattern, 
        therefore it has to be a pointer-accessed heap allocated object **/
    std::unique_ptr< Engine > m_engine;
};

Or:

class A
{
    class Impl;

    std::unique_ptr< A::Impl > m_impl; // PIMPL idiom
};

If an instance of a class Car is constant , why the Engine should not be constant as well? If it was a shared pointer I would have been completely fine with that.

Is there a smart pointer who can reflect the behaviour I want?

It's pretty simple:

const auto ptr = std::make_unique< A >();

This means that the pointer itself is constant! But the object it holds is not. You can see it working the other way around...

A *const ptr = new A();

It's the same. The pointer is constant (can't be modified to point elsewhere), but the object is not.

Now, you probably meant that you want something like this, no?

const auto ptr = std::make_unique<const A>();

This will create a constant pointer to a constant A .

There's also this other way...

auto ptr = std::make_unique<const A>();

The object is constant, but not the pointer.

BTW : That "const-propagation" you talk about applies to C++, too, in the same way you stated it.

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