I've been given this as a .H file for homework, and I'm tasked with creating the .C to go with it. It's really simple stuff, I'm sure I'm missing something small.
#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
In my constructor, when I try to set the value of the SharedCString's count to 1, I get a segmentation fault.
I was trying to pass it using:
shared->count = 1;
I'm not sure why this doesn't work.