【发布时间】:2021-02-10 13:46:59
【问题描述】:
您好,我在尝试运行以下命令时遇到内存访问冲突的运行时错误:
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 之后的第二个构造函数上得到它:
在 ConsoleApplication1.exe 中的 0x7C1436C0 (vcruntime140d.dll) 处引发异常:0xC0000005:访问冲突读取位置 0x011FDFA0。发生了
【问题讨论】:
-
为什么不使用适当的参数类型
const std::string&,并避免强制转换? -
您不应该将 C 风格的字符串 (
"Hello") 转换为标准的string。
标签: c++ constructor constants member initializer