c++ - 如果我公开 const 和非 const API,我是否会破坏 const 正确性?

标签 c++ constants const-correctness

我正在设计一个类,并对常量正确性有一些担忧,但我认为我并没有完全理解这个概念的真正含义。如果我存储一个指向非常量类型的原始指针,并希望为该指针提供常量和非常量访问器,这会破坏常量正确性吗?

class A
{
public:
    void SetCount(int* pCount)
    {
        m_pCount = pCount;
    }

    void GetCount(const int** ppCount) const
    {
        *ppCount = m_pCount;
    }

    void GetCount(int** ppCount) const
    {
        *ppCount = m_pCount;
    }

private:
    int* m_pCount = nullptr;
};

int main()
{
    int count = 10;

    A a;
    a.SetCount(&count);

    const int* pCountConst = nullptr;
    a.GetCount(&pCountConst);

    // Prints 10.
    std::cout << *pCountConst << std::endl;

    int* pCountNonConst = nullptr;
    a.GetCount(&pCountNonConst);
    (*pCountNonConst)++;

    // Prints 11.
    std::cout << *pCountConst << std::endl;
}

pCount 的类型是 const int*,因此我们期望底层 int 一旦初始化就永远不会改变。在我看来,我们在这里打破了常量正确性,是真的吗?

最佳答案

这取决于您的语义,但我认为我不会使用您在这里拥有的功能。相反,我会考虑以下两个选项:

如果您希望 A 拥有这个计数变量,那么您可能应该保留 const - 访问它时。在这种情况下,您可以这样编写函数:

void GetCount(const int** ppCount) const
{
    *ppCount = m_pCount;
}

void GetCount(int** ppCount) // note - omitted const
{
    *ppCount = m_pCount;
}

这意味着如果您有非 const A你可以获得一个非常量计数器,但如果你有一个 const A你只能得到const计数器。


您也可能意味着 A 只是观察一些计数变量。在这种情况下,const观察者意味着您不会更改所指向的 int,但该事物本身可能会发生变化。在这种情况下,您可以像这样编写访问器:

void GetCount(int** ppCount) const
{
    *ppCount = m_pCount;
}

一般来说,我会说更喜欢第一种方法并保留 const -ness,但另一种方式在某些情况下肯定是有效的。

关于c++ - 如果我公开 const 和非 const API,我是否会破坏 const 正确性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58350920/

相关文章:

c++ - GNU Make 产生完全不同的结果

java - 为什么 final Byte 作为 switch 语句中的 case 不能编译?

c++ - 常量引用不是 "updated"

c++ - const 正确性

c++ - 为什么将 "pointer to pointer to non-const"转换为 "pointer to pointer to const"是不合法的

c++ - 为什么我可以从 const 方法调用更改成员的方法?

c++ - 相对标题 XCode 4

c++ - 循环遍历 vector 时将对象添加到 vector

c++ - 如何确保执行相同功能的两个线程互斥

c# - 如何从字符串变量创建常量字符串