关于c ++智能指针的分段错误?

问题描述 投票:-2回答:1

你好,我是c ++的新手。今天当我测试我的代码项目时,我遇到了一个让我感到困惑的问题。

我想在我的解析JSON项目中使用智能指针,所以我将一行字符串传递给类:json_content,我想要json_contentjson_value的成员来获取字符串。编译器没有给我任何警告或错误,但是当我运行a.out文件时,它告诉我segmentation fault。我在谷歌搜索了很多,但是我找不到任何解决这个问题的方法。任何人都可以帮助我吗?非常感谢! :)

BTW,我的操作系统是MacOSX x86_64-apple-darwin18.2.0,编译器是Apple LLVM version 10.0.0 (clang-1000.10.44.4)

这是代码:

#include <string>
#include <iostream>
#include <memory>
#include <typeinfo>
using namespace std;

class json_content {
    public:
    string json_value;
};

int main()
{
    shared_ptr<json_content> c;
    shared_ptr<string> p2(new string("this is good"));

    // segmentation fault
    c->json_value = *p2;
    // this is also bad line!
    c->json_value = "not good, too!";

    return 0;
}

c++ shared-ptr smart-pointers
1个回答
4
投票

默认情况下,shared_ptrnullptr(参见API)。你无法取消引用nullptr。你需要先初始化c

#include <string>
#include <iostream>
#include <memory>
#include <typeinfo>

using namespace std;

class JsonContent {
 public:
  string json_value;
};

int main() {
  shared_ptr<JsonContent> c = std::make_shared<JsonContent>();
  shared_ptr<string> p2 = std::make_shared<string>("This is good.");

  c->json_value = *p2;
  c->json_value = "This is also good!";
  cout << c->json_value << endl;
  return 0;
}

但是:ku zxsw。

© www.soinside.com 2019 - 2024. All rights reserved.