I have a struct that has a pointer as member:
struct MyStruct {
char *ptr;
}
I want to initialize the ptr in a scope and then be able to use it outside of that scope:
{ // scope 0
{ //scope 1
{ // scope 2
mystruct.ptr = new char[100];
}
// mystruct.ptr still lives here
}
// i dont need mystruct anymore
delete[] mystruct.ptr;
}
But then I have to delete it later, which is error prone and I would rather avoid having to do this. So I thought to use std::shared_ptr
.
{ // scope 0
{ //scope 1
{ // scope 2
auto a = std::make_shared<char>(new char[100]);
mystruct.ptr = a.get(); // ??????? HOW TO ASSIGN
}
// mystruct.ptr still SHOULD live here
}
}
So, how could I do it? How should I assign shared_ptr to mystruct.ptr so that the ownership count becomes 2? I see that get() does not work, because it just passers the pointer but not gives ownership, so it is deleted.
As you see, the main motivation here is to extend the lifetime, so I am open to other practices. Maybe I am wrong about thinking in using shared_ptr here?