简体   繁体   中英

Can we store the class object and not just the pointer to that object

I was trying to store the class object in a file but as the class contains a vector of pointers which is causing a trouble because next time I am accessing the class I am able to fetch everything but this vector.

typedef vector<pair<int, MBR *>> vppint;

class Node{
private:
  int id;
  int parentID;
  int total_children;
  MBR *mbr;
  vppint children;
public:
  vppint fetchChildren(){
    return return this->children;
  }

  int totalChildren(){
    return this->total_children;
  }
};

MBR is some class.

after storing this Node class in the file and then reading it. the fetchChildren function throws segmentation fault with the obvious reason. is there any way to store the object and not just the pointer.

In C++ you can work with Constructors and Destructors if you would want to create / destroy an instance of a class (I believe those are not needed but it could help you understand how it works).

You can do so by declaring a public constructor in your node class. And then declare the function. Node::Node() {} which in our case will be empty.

class Node{
private:
  int id;
  int parentID;
  int total_children;
  MBR *mbr;
  vppint children;
public:

  Node();
  vppint fetchChildren(){
    return return this->children;
  }

  int totalChildren(){
    return this->total_children;
  }
};

When you have a constructor which will initialize values (or if you prefer to not use a constructor) you can simply store the class object alike:

Node savedObject = Node(); // Creates an instance of the Node class.

If this is what you want to achieve I would suggest you read something as: https://www.w3schools.com/cpp/cpp_constructors.asp for more information.

That's C++. Until now you have to write your own serialization logic which handles pointers correctly. You can take a look at boost::serialization , what provides a lot of helper functions. Note that boost::serialization makes your serialization tool output platform dependet. If you want crossplatform serialization, you have to either put some more effort into your seriaization logic or make use of something like protobuf .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM