请澄清const限定符传播

Vic*_*voy 1 c++

假设我们有以下代码:

class Base {
  public:
    int a = 5;
};

class Derived : public Base {
  public:
    Base *parent_ = new Base;
    Base* parent() const { return parent_; }
};

void f(const Derived *derived) {
    Base *p = derived->parent();
    p->a = 10; // <- is this correct?
}
Run Code Online (Sandbox Code Playgroud)

我个人认为这是一个问题:

在函数中,f我们采用指向const类对象的指针Derived.这使得它的每个成员也const因而parent_变得const Base *.如果它是const,我们就不应该有能力修改指针指向的对象.

我哪里错了?

son*_*yao 7

这使得它的每个成员也因此parent_成为const Base *.

不,指针将成为const本身,而不是它指向的对象.所以parent_变成了Base * const,而不是const Base *,你的代码是有效的.


Aja*_*jay 5

Base* parent() const { return parent_; }
Run Code Online (Sandbox Code Playgroud)

不幸的是,这是C ++的问题。方法是const,但是它返回一个非常量指针,这将使以下操作成功:

p->a = 10; // <- is this correct?
Run Code Online (Sandbox Code Playgroud)

程序员的责任是不从函数返回非常量指针或引用(方法是否为常量)。