gpt4 book ai didi

c++ - 唯一指针和 const 正确性

转载 作者:可可西里 更新时间:2023-11-01 18:17:05 27 4
gpt4 key购买 nike

我没想到这段代码可以编译:

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

有没有智能指针可以反射(reflect)我想要的行为?

最佳答案

这很简单:

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++,就像您所说的那样。

关于c++ - 唯一指针和 const 正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33565163/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com