private:
// data containing character strings
// shared by Strings when copying/assigning
struct SharedData
{
char *data; // 0-terminated char array
size_t n; // number of non-0 characters in string
size_t count; // reference count, how many Strings share this object?
};
SharedData *shared; //here i don't understand how to use.
How do I use n?
do I just do this
shared -> n = 3;
I keep getting segmentation faults so i don't know what i am doing. I want to grab the length of a string and then pass it to n to be stored
Your class contains a pointer to SharedData. You need to make that pointer point to something, presumably by doing this
shared = new SharedData();
shared->n = 3;
// etc.
Same thing is true of data inside shared
shared->data = new char[100];
strcpy(shared->data, ...);
I have a feeling this is going to be quite a hard exercise for you if you don't have a good grasp of pointers yet.
You should allocate some memory first:
SharedData *shared = new SharedData;
shared->n = 3;
Better use something like this:
struct SharedData {
SharedData(size_t Capacity) : data(0), capacity(Capacity), length(0), count(1) {
data = new char[capacity];
}
~SharedData() {
if (--count <= 0) delete [] data;
}
char *data; // 0-terminated char array
size_t length; // number of non-0 characters in string
size_t capacity;
size_t count; // reference count, how many Strings share this object?
};
SharedData* shared = new SharedData(1000);
Edit: Of course this short example lacks of copy constructor and handle reference counting in appropriate manner. But this is not subject of this answer.
Modifying an un-allocated point in memory is undefined behavior.
You must allocate memory for shared
or set it to a valid address.
class Class
{
private:
SharedData *shared;
...
public:
Class() : shared(new SharedData()) {}
~Class() { delete shared; }
void doSomething() { shared->n = 3; }
};
Try not to use bare pointers when you can use smart pointers:
class Class
{
private:
std::unique_ptr<SharedData> shared;
or
std::shared_ptr<SharedData> shared;
...
public:
Class() : shared(new SharedData()) {}
void doSomething() { shared->n = 3; }
};
Are you using a C++11 compiler? Why don't you make it a bit easier?
struct SharedData
{
std::string data;
size_t count; // reference count, how many Strings share this object?
};
std::shared_ptr<SharedData> shared = std::make_shared<SharedData>();
If you don't need the actual count of the number of referrers, you just want to know if there is anyone referencing your data, simply use a std::shared_ptr<std::string>
. It will keep track of references and destroy the string object when all the references are gone.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.