C++字符串无法读取内存

C++ String Unable to Read Memory

本文关键字:读取 内存 字符串 C++      更新时间:2023-10-16

我有一个类,如下所示:

class ModelCommand {
public:
    virtual ~ModelCommand() {};
};
class FolderCommand : public ModelCommand {
public:
    std::string text;
    unsigned width;
    bool isBackspace;
    FolderCommand(bool isBackspace, unsigned width, std::string text = "") : text(text), width(width), isBackspace(isBackspace) {}
};
class CModel {
private:
    string _folder;
public:
    void Update(std::shared_ptr<ModelCommand> &cmd);
};

然后在我的控制器中,我有一个模型的实例,并使用我创建的新FolderCommand对象更新它:

shared_ptr<CModel> model;
shared_ptr<ModelCommand> cmd = dynamic_pointer_cast<ModelCommand>(make_shared<FolderCommand>(false, 20, "a"));
model->Update(cmd);

然后在我的CModel更新方法中,我尝试做以下操作:

void CModel::Update(std::shared_ptr<ModelCommand> &cmd) {
    if (auto folderCmd = dynamic_pointer_cast<FolderCommand>(cmd)) {
        if(!folderCmd->isBackspace)
            // This is where _folder is unable to read memory
            _folder += folderCmd->text;
        else if(folderCmd->isBackspace && _folder.length() > 0)
            _folder.erase(--_folder.end());
        folderCmd->text = _folder;
    }
}

这导致CModel的_folder变量为"无法读取内存"。

有人能解释并提供这个问题的解决方案吗?

谢谢。

更新添加了更多用于澄清的代码

使用您发布的第一个片段,我调用了如下的Update方法,没有出现"无法读取内存"的问题。

int main()
{
  shared_ptr<ModelCommand> fc(new FolderCommand("somestring\"));
  CModel mod;
  mod.Update(fc);
  mod.print_folder();
  return 0;
}

我想看看Update方法是如何使用的会很有趣。

Obs.:我添加了一个公共成员函数print_folder,用于打印_folder私有成员。此外,我只想发表一点评论,但我仍然没有这个特权。