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?
ptr->set( 666 ); // I do not like this line D:<
: Quote of the Day ;). – Unifilar