I'm trying to understand the concept behind pointers. I have a function in which i set an pointer to an object as an attribute of a struct:
void util::setobject(string s)
{
Document* d;
d->Parse(s.c_str());
message.payload = d;
{
Outside this function i can call the message object and access the document. Now I call this function for the second time so I overwrite the payload and set a new pointer to a new document. As far as I know, the old document object still exists but nothing points to it correct? Is this object then removed automatically? Thanks!
Edit
Sorry I totally messed up this code example. So I have two options here:
Option 1: Stay with pointers
void util::setobject(string s)
{
Document* d = new Document();
d->Parse(s.c_str());
message.payload = d;
{
To avoid a memory leak i would need to delete the pointed object before assigning new value, correct?
void util::setobject(string s)
{
Document* d = new Document();
d->Parse(s.c_str());
delete message.payload; // correct?
message.payload = d;
{
Second option: Avoid using "new"
void util::setobject(string s)
{
Document d;
d.Parse(s.c_str());
message.payload = d; // object is copied to struct attribute
{
S.th. like that wouldn't work because d goes out of scope:
void util::setobject(string s)
{
Document d;
d.Parse(s.c_str());
message.payload = &d; // does not make sense correct?
{
This might be s.th. off-topic, but the second version would require the struct to look like that:
struct MESSSAGE
{
string topic;
bool done = true;
Document payload;
}
Document comes from <rapidjson/document.h>. Doing it without a pointer results in multiple errors:
error: use of deleted function 'Message::Message(const Message&)'
'rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>::GenericDocument(const rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>&) [with Encoding=rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>; StackAllocator=rapidjson::CrtAllocator]' is private within this context
Does anyone also know how to interpret these errors? I think that the copy constructor of Document is private, therefore I need to use pointer here, correct?