我没想到这段代码会编译:
#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;
}
如果ptr是一个原始的 C 指针,我会同意的。但由于我使用的是智能指针,我无法理解这背后的基本原理是什么。
我使用唯一指针来表达所有权,在面向对象编程中,这可以看作是一个对象组合(“部分”关系)。
例如:
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;
};
或者:
class A
{
class Impl;
std::unique_ptr< A::Impl > m_impl; // PIMPL idiom
};
如果 Car 类的实例是常量,为什么 Engine 也不应该是常量?如果它是一个共享指针,我完全可以接受。
有没有可以反映我想要的行为的智能指针?