[英]c++ member initializer with const getter in a class
嗨,我在尝试运行以下命令时收到内存访问冲突的运行时错误:
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。 发生了
您应该避免 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.