tags:

views:

341

answers:

2

Write pointer to string,delete pointer,and load pointer from string?

+7  A: 

It's possible, but it won't do what you think it will do. Saving entire object as a string is called serialization - see Boost.Serialization (or Protocol Buffers, as suggested in comments) if you need that.

PiotrLegnica
Prefer Google Protocol Buffers if possible: http://code.google.com/intl/fr/apis/protocolbuffers/docs/overview.html, it is best to decorrelate the serialization/deserialization structure from the object itself for forward/backward compatibility.
Matthieu M.
+14  A: 

It's possible to do those operations, but they won't have the effect you're (probably) after.

Writing the pointer to string will only store the pointer value, i.e. the address of the pointed-to object. This is a string of more or less constant length, like 0x7f2b93c91780 (on a 64-bit system). Naturally, this doesn't capture any of the state of the actual object.

When you use delete on the pointer, the memory pointed at will be returned to the system; it's no longer yours to use. The pointer itself is not deleted, the operation only affects the memory being pointed at. Also, the pointer's value doesn't actually change when you use delete on it. Thus, there's no difference if you now re-load it by reading it in from a string stored somewhere else: it's still pointing at memory you no longer own, and thus can't read or write without invoking undefined behavior.

Like PiotrLegnica suggested, you need to serialize the entire object into a string, and then re-create the object from the serialized version (de-serialize it).

unwind
Actually, when you say `delete ptr`, you do not delete the pointer, but the value it points to. The pointer object itself is only deleted when it goes out of scope. So "deleting a pointer" (usually) is not a correct term. Other than that, I totally agree with your answer. +1
sbi
@sbi: I guess I'm blinded by the commonality, I really do think and say "delete the pointer", although I of course know that the pointer itself is not what is deleted ... I tried being more precise.
unwind
@unwind: This was merely a minor point. (Although I think being precise often helps, especially when answering questions of newbies who obviously have problems wrapping their heads around pointers...)
sbi