简体   繁体   English

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

[英]C++ String Unable to Read Memory

I have a class that looks like the following: 我有一堂课,看起来像下面这样:

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);
};

Then in my controller I have an instance of my model and update it using the new FolderCommand object I create: 然后在我的控制器中,我有一个模型实例,并使用我创建的新FolderCommand对象对其进行了更新:

shared_ptr<CModel> model;

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

model->Update(cmd);

And then inside my update method of CModel I try to do the following: 然后在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;
    }
}

This results in the CModel's _folder variable being "Unable to Read Memory". 这导致CModel的_folder变量为“无法读取内存”。

Can someone explain and provide a solution to this problem? 有人可以解释这个问题并提供解决方案吗?

Thanks. 谢谢。

UPDATE Added some more code for clarification UPDATE添加了更多代码以供澄清

Using the first snippet you posted, I called the Update method as below, and no "Unable to Read Memory" issue arose. 使用您发布的第一个代码片段,我如下调用了Update方法,并且没有出现“无法读取内存”的问题。

int main()
{
  shared_ptr<ModelCommand> fc(new FolderCommand("somestring\\"));
  CModel mod;

  mod.Update(fc);
  mod.print_folder();

  return 0;
}

I think that would be interesting to see how the Update method is being used. 我想看看如何使用Update方法会很有趣。

Obs.: I added a public member function, print_folder, to print ou the _folder private member. 观察:我添加了一个公共成员函数print_folder来打印_folder私有成员。 Also, I'd make just a comment, however I still don't have this privilege. 另外,我只是发表评论,但是我仍然没有此权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM