Hi I get the runtime error with memory acccess violation when trying to run the following:
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;
}
and the error I get is beloow I get it on the seconde constructor after m_debugcount:
Exception thrown at 0x7C1436C0 (vcruntime140d.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation reading location 0x011FDFA0. occurred
You should avoid c-style casts and use static_cast
instead as it is safer. Changing your code to use static_cast
:
const MyMutable k(static_cast<std::string&>("Hello"));
Results in the error:
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"));
The solution is to change your constructor to take a const
reference then you don't need to cast at all as the string literal is automatically converted to 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;
}