用 const_cast 在 class 中分配非静态常量成员

assign non-static const member in class with const_cast

为什么可以使用 const_cast 分配非静态 const 成员,这在什么时候有用?

在下面的代码中,A 和 B 类 都能正常编译和工作。但是,对于 B,它的 const 成员 s 并没有在构造函数中使用初始化列表进行初始化,而是通过使用 const_cast 删除 const 并通过引用传递给它一个值。也可以写成(string&)s = _s;

我不常在作业的左侧看到 const_cast,但这个似乎工作正常。 B的构造器的优缺点是什么?

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

class A {
public:
    A(const string& _s) : s(_s) {}
    void display() {cout << s << endl;}
private:
    const string s;
};

class B {
public:
    B(const string& _s) {
        const_cast<string&>(s) = _s;
    }
    void display() {cout << s << endl;}
private:
    const string s;
};

int main() {
    A a("abc");
    a.display();
    B b("def");
    b.display();
    return EXIT_SUCCESS;
}

输出:

abc
def

Why can a non-static const member be assigned using const_cast, and when would this be useful?

取决于"can"的意思。

程序格式正确,因为您修改了一个非常量左值。

程序的行为未定义,因为您修改了一个 const 对象。

and when would this be useful?

修改 const 对象永远不会有用。

有时(尽管很少)从引用中抛出 const 是有用的,这就是 const_cast 存在的原因。但它只有在你有一个非常量对象的常量引用时才有用。

What are the pros ... of B's constructor?

None.

What are the ... cons of B's constructor?

如果调用 B 的构造函数,程序的行为是未定义的。