c++ - 如何通过 std::unique_ptr 成员调用其他类的 const 成员函数

标签 c++ c++11 type-conversion smart-pointers unique-ptr

在阅读有关向标准库添加 const-propagating 包装器的提案(文档编号 N4388 )时,我碰到了论文中给出的示例:

#include <memory>
#include <iostream>

struct A
{
    void bar() const
    {
        std::cout << "A::bar (const)" << std::endl;
    }

    void bar()
    {
        std::cout << "A::bar (non-const)" << std::endl;
    }
};

struct B
{
    B() : m_ptrA(std::make_unique<A>()) {}

    void foo() const
    {
        std::cout << "B::foo (const)" << std::endl;
        m_ptrA->bar(); // calls A::bar() (non-const)

        // const_cast<const std::unique_ptr<A>>(m_ptrA)->bar(); // how to call the A::bar() const?
    }

    void foo()
    {
        std::cout << "B::foo (non-const)" << std::endl;
        m_ptrA->bar();
    }

    std::unique_ptr<A> m_ptrA;
};

int main()
{
    const B const_b;
    const_b.foo();
}

哪些输出:

B::foo (const)
A::bar (non-const)

我明白为什么会这样。即使指针是const,它指向的对象也是非常量的,所以确实调用了非常量成员函数A::bar(这是整个论文中提案的重点,以避免这种看似尴尬的情况并通过包装器传播 const )。此外,他们说为了避免这种情况,一旦可以const_cast B::foo() const 中的指针m_ptrA,所以它调用所需的 A::bar() const

我尝试了无数种组合,但坦率地说,我不知道如何const_cast unique_ptr。即,我如何在 B::foo() const 中通过 m_ptrA 强制执行对 A::bar() const 的“正确”调用>? (如果我不完全清楚我想要什么,另请参阅代码中的注释)。

最佳答案

您需要对存储的指针进行常量转换,而不是unique_ptr:

const_cast<const A*>(m_ptrA.get())->bar();
const_cast<const A&>(*m_ptrA).bar();

关于c++ - 如何通过 std::unique_ptr 成员调用其他类的 const 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29682763/

相关文章:

c++ - 我可以制作一个具有相同签名的 String + lambda 表吗?

c++ - 具有非类型模板参数的通用打印机

c++ - 如何实现 "const"和 "non-const"重载而不重复代码?

string - 如何在 Go 中将 uint16 转换为 2 字节字符串?

android - Cocos2dx 构建问题

c++ - 用于事件调度程序的 STL 容器

c# - 当通过 C# 调用 C++ DLL 的导出类时,该类的 C 样式字符串成员在一个导出函数中是 OK,但在另一个函数中不是

c# - Delphi7中使用的C++ DLL函数

c - 为什么 printf 打印出错误的值?

c++ - 动态内存的后期绑定(bind)