user1899020
user1899020

Reputation: 13575

How to read and write shared_ptr?

When my data use shared_ptr which is shared by a number of entries, any good way to read and write the data to show the sharing? For example

I have a Data structure

struct Data
{
    int a;
    int b;
};

Data data;
data.a = 2;
data.b = 2;

I can write it out in a file like data.txt as

2 2

and read the file, I can get the data with values a = 2 and b = 2. However if the Data uses share_ptr, it becomes difficult. For example,

struct Data
{
    shared_ptr<int> a;
    shared_ptr<int> b;
};

Data data;

data can be

data.a.reset(new int(2));
data.b = data.a;

or

data.a.reset(new int(2));
data.b.reset(new int(2));

The 2 cases are different. How to write the data to the data.txt file and then read the file to the data, I can get the same data with the same relations of a and b?

Upvotes: 0

Views: 477

Answers (1)

jxh
jxh

Reputation: 70382

This is a kind of data serialization problem. Here, you want to serialize your Data that has pointer types within it. When you serialize pointer values, the data they are pointing to is written somewhere, and the pointers are converted into offsets to the file with the data.

In your case, you can think of the int values as being written out right after the object, and the "pointer" values are represented by the number of bytes after the object. So, each Data in your file could look like:

|total-bytes-of-data|
|offset-a|
|offset-b|
|value[]|

If a and b point to the same instance, they would have the same offset. If a and b point to different instances, they would have different offsets.

I'll leave as an exercise the problem of detecting and dealing with sharing that happens between different Data instances.

Upvotes: 1

Related Questions