在类中带有const getter的C ++成员初始化程序

问题描述

嗨,我在尝试运行以下命令时遇到运行时错误,并显示内存访问冲突:

class MyMutable{
private :
    std::string m_name;
    mutable int m_DebugCount;
public:
    MyMutable()
        : m_name(" "),m_DebugCount(0) {}

    MyMutable(std::string& newName)
        : m_name(newName),m_DebugCount(0) {}

    std::string getName() const
    {
        ++m_DebugCount;
        return m_name;
    }
};

int main()
{
    const MyMutable k((std::string&)("Hello"));
    std::cout << k.getName() << std::endl;
}

我得到的错误是在m_debugcount之后的seconde构造函数上得到的:

在ConsoleApplication1.exe中的0x7C1436C0(vcruntime140d.dll)处引发的异常:0xC0000005:访问冲突读取位置0x011FDFA0。发生

解决方法

您应该避免使用C样式强制转换,而应使用static_cast,因为这样做更安全。更改代码以使用static_cast

const MyMutable k(static_cast<std::string&>("Hello"));

导致错误:

error: non-const lvalue reference to type 'std::string' (aka 'basic_string<char>') cannot bind to a value of unrelated type 'const char [6]'
    const MyMutable k(static_cast<std::string&>("Hello"));

解决方案是将构造函数更改为采用const引用,然后您就不需要强制转换,因为字符串文字会自动转换为std::string

#include <string>
#include <iostream>

class MyMutable{
private :
    std::string m_name;
    mutable int m_DebugCount;
public:
    MyMutable()
        : m_name(" "),m_DebugCount(0) {}

    MyMutable(const std::string& newName)
        : m_name(newName),m_DebugCount(0) {}

    std::string getName() const
    {
        ++m_DebugCount;
        return m_name;
    }
};

int main()
{
    const MyMutable k("Hello");
    std::cout << k.getName() << std::endl;
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...