Unique pointer and constant correctness

I did not expect 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 fine. But since I use a smart pointer , I can not understand what is the reason for this.

I use a unique pointer to express ownership , in object-oriented programming this can be seen as a composition of the object ("part of the relationship").

For instance:

 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 the Car class has a constant value, why shouldn't the Engine be constant? If it were a general index, I would be completely at it.

Is there a smart pointer that can reflect the behavior I want?

+5
source share
1 answer

It is pretty simple:

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

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

 A *const ptr = new A(); 

Same. The pointer is constant (it cannot be changed to indicate elsewhere), but the object is not.

Now you probably meant that you wanted something like that, no?

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

This will create a constant pointer to constant A

There is also this other way ...

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

The object is permanent, but not a pointer.

BTW . That the "const propagation" you are talking about applies to C ++, just as you stated it.

+11
source

Source: https://habr.com/ru/post/1235357/


All Articles