Is it safe to store reference/pointer on uninitialized data member? Not use, but store at some moment of time.
I know that I have to use smart pointers. But for code simplicity I decide to give an example with owning raw pointers. Which is not very good in practice but I think good enough for example.
Here is the example of code:
struct Node {
Node(Node*& node_ptr) : list_first_node_ptr{node_ptr} {}
Node*& list_first_node_ptr;
};
struct List {
// Is this line - dangerous?
List() : first_node_ptr{new Node{first_node_ptr}} {}
Node* first_node_ptr;
~List() {delete first_node_ptr;}
};
I initialize first_node_ptr
with Node
object, but pass in constructor of Node
object still not uninitialized first_node_ptr
.
One more question: is memory already allocated for first_node_ptr
when I pass it, so will the reference address at Node
constructor be valid?
I think that this example is about the same but simplified version. I'm right?
class Base {
public:
// var_ptr points to uninitialized va
Base() : var_ptr{&var}, var{10} {}
int* var_ptr;
int var;
};
P.S. Why when I write (Node*)&
instead of Node*&
I get compilation errors about incomplete type?
P.P.S. Can the usage of smart pointers change the situation?
Aucun commentaire:
Enregistrer un commentaire