【问题标题】:C++ unable to remove constant of an object iin recursiveC ++无法以递归方式删除对象的常量
【发布时间】:2016-08-23 03:34:18
【问题描述】:

我有以下功能

class p{
public :
string const& PrintData() const
{
    cout << "const" << str;
    const_cast<ConstFunctions *>(this);
    PrintData();
    return str;
}
string const& PrintData()
{
    cout << "non-const" << endl;
    return str;
}
private :
string str="Hello";
}

int main()
{
const p p1;
p1.PrintData();
}

我期待以下 ::

const你好 非常量你好

因为我去掉了对象的不变性

但我正在进入无限递归循环

【问题讨论】:

    标签: c++ constants const-cast


    【解决方案1】:

    声明const_cast&lt;ConstFunctions *&gt;(this); 没有做任何有用的事情。它执行const_cast 并简单地丢弃结果。编译器很可能会将其优化掉。

    然后你进行递归调用,它只会调用自己,而不是非常量函数。

    你可能打算这样做

    const_cast<p*>(this)->PrintData();
    

    【讨论】:

    • “编译器很可能会优化掉它。” 编译器绝对会“优化掉它”,因为实际上没有可以为它创建的有意义的代码那句话。它在翻译/“编译”程序中没有类似物。
    • 实际上是 const_cast&lt;p*&gt;(this)-&gt;PrintData()(不知道 ConstFunctions 是什么)
    • 如果我想永久删除对象的恒定性怎么办?有可能吗?
    • @raghureddy 这不可能。
    • 感谢您的快速回复。我会对此做更多的研究
    【解决方案2】:

    这一行...

    string const& PrintData() const
    {
        cout << "const" << str;
        const_cast<ConstFunctions *>(this);   //It doesn't work this way, you didn't use the result
        PrintData();     //THis causes a recursive loop
        return str;
    }
    

    你有一个递归问题,你没有捕捉到 const_cast 的返回值,因此结果被丢弃,编译器将优化该行。

    看,每当你在代码中调用像 PrintData() 这样的成员函数时,它都会像这样调用

    this->PrintData();
    //actually, like 
    p::PrintData( /*cv*/ this); //The cv qualification of 'this' depends on the cv of the object, in your case, const
    

    this 指针始终带有调用对象的cv 限定符。见What does "cv-unqualified" mean in C++?

    您要做的是丢弃thiscv 资格并使用生成的this 调用非常量版本

    string const& PrintData() const
    {
        cout << "const" << str;
        return const_cast<p*>(this)->PrintData();
    }
    

    【讨论】:

    • 谢谢,很有帮助。
    【解决方案3】:

    p1const,所以它调用:

    string const& PrintData() const
    

    在这个函数中你调用PrintData,但是因为你在一个const函数中,编译器会调用你的const版本,这将导致递归循环。

    行:

    const_cast<ConstFunctions *>(this);
    

    实际上没有做任何事情,因为您的类在其类型层次结构中没有这种类型,而且您也没有对 in 做任何事情。

    如果你真的想调用非常量版本,那么这样做:

    const_cast<p*>(this)->PrintData();
    

    但是你真的应该问问自己为什么要这样做......

    【讨论】:

    • 谢谢,很有帮助。
    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多