问题描述
嗨,我在尝试运行以下命令时遇到运行时错误,并显示内存访问冲突:
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;
}