我沒想到這個代碼編譯:唯一指針和const正確性
#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的實例是不斷,爲什麼不引擎應該是恆定的呢?如果這是一個共享指針,我會完全正確的。
有沒有可以反映我想要的行爲的智能指針?
'ptr-> set(666); //我不喜歡這一行D:<':每日報價;)。 – 3442