7

我没想到这段代码会编译:

#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 也不应该是常量?如果它是一个共享指针,我完全可以接受。

有没有可以反映我想要的行为的智能指针?

4

1 回答 1

20

这很简单:

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

这意味着指针本身是恒定的!但它持有的对象不是。你可以看到它以相反的方式工作......

A *const ptr = new A();

一样的。指针是常量(不能修改为指向别处),但对象不是。

现在,你可能的意思是你想要这样的东西,不是吗?

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

这将创建一个指向常量的常量指针A

还有这个方法...

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

对象是常量,但不是指针。

顺便说一句:你所说的“const-propagation”也适用于 C++,就像你所说的那样。

于 2015-11-06T11:01:55.160 回答