【问题标题】:c++ member initializer with const getter in a classc++ 成员初始化器与类中的 const getter
【发布时间】: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&amp;,并避免强制转换?
  • 您不应该将 C 风格的字符串 ("Hello") 转换为标准的 string

标签: c++ constructor constants member initializer


【解决方案1】:

您应该避免使用 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多