我收到了一个 .H 文件作为家庭作业,我的任务是创建 .C 来配合它。这真的很简单,我确定我遗漏了一些小东西。
#ifndef String_H
#define String_H
#include <iostream>
class String
{
public:
// constructor: initializes String with copy of 0-terminated C-string
String(const char *p);
// destructor (when can shared data be released?)
~String();
// copy constructor (how does this change reference counts?)
String(const String &x);
// assignment operator (how does this change reference counts?)
String &operator=(const String &x);
// return number of non-0 characters in string
int size() const;
// return reference count
int ref_count() const;
// returns pointer to character array
const char *cstr() const;
private:
// data containing character strings
// shared by Strings when copying/assigning
struct SharedCString
{
char *data; // 0-terminated char array
int n; // number of non-0 characters in string
int count; // reference count, how many Strings share this object?
};
SharedCString *shared;
};
#endif
在我的构造函数中,当我尝试将 SharedCString 的计数值设置为 1 时,出现了段错误。
我试图通过以下方式传递它:
shared->count = 1;
我不确定为什么这不起作用。
最佳答案
如果在线上出现段错误
shared->count = 1;
然后 shared
为 NULL 或者是垃圾,指向您的进程不拥有的内存。
你应该这样做
shared = new SharedCString;
在访问它之前。
关于c++ - 传递值时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12611537/