Info
This post was imported from a personal note. It may contain inside jokes, streams of consciousness, errors, and other nonsense.
Funny way to learn about smart pointers and start using them.
Cereal does not support serializing raw pointers - please use a smart pointer
std::unique_ptr is for a single pointer. When the pointer variable goes out of scope the object will be destroyed. You can’t copy the pointer but you can move it like so:
std::unique_ptr<int> valuePtr(new int(15));
std::unique_ptr<int> valuePtrNow(std::move(valuePtr));
The value is still accessed using the dereference operator. *valuePtrNow
. Looks like you can also cast it to a bool to determine whether the pointer has an object.
static_cast<bool>(valuePtr)
shared_ptr. Reference counting pointer for sharing outside a class. When references drop to zero the object is deleted.
I should change my pointers to shared pointers for the most part.
weak_ptr. Holds a reference that does not take ownership of the resource. Looks like you make a weak pointer from a shared pointer. But if no other references to the resource exist, it will be deleted and your weak pointer will be useless. Before you can access the resource with a weak pointer, you need to call .lock()
which returns a shared pointer which does increment the reference count. Neat.
Back to Cereal #
I was getting an error trying to Cerealize a vector of Boids. Turns out I needed to include specific header files from Cereal. Keep it in mind.
#include <cereal/types/memory.hpp>
#include <cereal/types/vector.hpp>
Also, I used CEREAL_NVP()
to get better member variable names into the output file. Looks like this in JSON:
"id": 2147483658,
"data": {
"id": 9,
"generationIndex": 0,
"numFoodsEaten": 0
}
Pretty sweet. Still got some more work to do to serialize the whole thing but this is great so far.