nya*_*108 7 c++ pointers smart-pointers const-correctness object-composition
我没想到要编译这段代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果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;
};
Run Code Online (Sandbox Code Playgroud)
要么:
class A
{
class Impl;
std::unique_ptr< A::Impl > m_impl; // PIMPL idiom
};
Run Code Online (Sandbox Code Playgroud)
如果Car类的实例是常量,为什么Engine也不应该是常量?如果它是一个共享指针我会完全没问题.
有没有一个智能指针可以反映我想要的行为?
344*_*442 15
这很简单:
const auto ptr = std::make_unique< A >();
Run Code Online (Sandbox Code Playgroud)
这意味着指针本身是不变的!但它拥有的对象不是.你可以看到它以相反的方式工作......
A *const ptr = new A();
Run Code Online (Sandbox Code Playgroud)
一样的.指针是常量(不能修改为指向别处),但对象不是.
现在,你可能意味着你想要这样的东西,不是吗?
const auto ptr = std::make_unique<const A>();
Run Code Online (Sandbox Code Playgroud)
这将创建一个指向常量的常量指针A.
还有另一种方式......
auto ptr = std::make_unique<const A>();
Run Code Online (Sandbox Code Playgroud)
对象是常量,但不是指针.
BTW:你所说的"const-propagation"也适用于C++,就像你说的那样.