用const_cast分配类中的非静态const成员

问题描述 投票:0回答:1

为什么不能使用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
c++ constructor const const-cast
1个回答
0
投票

为什么不能使用const_cast分配非静态const成员,这何时有用?

取决于您所说的“可以”。

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

由于修改了const对象,程序的行为是不确定的。

什么时候有用?

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

© www.soinside.com 2019 - 2024. All rights reserved.