簡體   English   中英

關於 C++ 智能指針的分段錯誤?

[英]Segmentation fault about c++ smart pointers?

你好,我是 C++ 的新手。 而今天我在測試我的代碼的一個項目時,遇到了一個讓我感到困惑的問題。

我想在我的解析 JSON 項目中使用智能指針,所以我將一行字符串傳遞給類: json_content ,我希望json_content的成員json_value來獲取字符串。 編譯器沒有給我任何警告或錯誤,但是當我運行 a.out 文件時,它告訴我segmentation fault 我在谷歌搜索了很多,但是我沒有找到任何解決這個問題的方法。 任何人都可以幫助我嗎? 非常感謝! :)

順便說一句,我的操作系統是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;
}

默認情況下, shared_ptrnullptr (請參閱API )。 nullptr引用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;
}

演示http : //cpp.sh/5fps7n

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM