指向未初始化数据成员的指针 [英] Pointer to 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.
这是代码示例:
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;}
};
我用Node
对象初始化了first_node_ptr
,但是传入Node
对象的构造函数仍然没有被未初始化的first_node_ptr
.
I initialize first_node_ptr
with Node
object, but pass in constructor of Node
object still not uninitialized first_node_ptr
.
另一个问题:我通过它时是否已经为first_node_ptr
分配了内存,那么Node
构造函数中的引用地址是否有效?
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;
};
PS
为什么当我写(Node*)&
而不是Node*&
时,我得到有关不完整类型的编译错误?
P.S.
Why when I write (Node*)&
instead of Node*&
I get compilation errors about incomplete type?
P.P.S. 使用智能指针可以改变情况吗?
P.P.S. Can the usage of smart pointers change the situation?
P.P.P.S. @JesperJuhl询问了用例. 这个想法是创建一个循环链表,其中每个节点在Head指针上都有指向第一个前哨节点的引用.我从CppCon视频2016 43:00中的 Herb Sutter中得到了这个想法.在视频中,他谈到了唯一的指针,但我举了一些原始指针的示例,这可能会变得有些混乱.
P.P.P.S. @JesperJuhl asked about use case. The idea is to create circular linked list where every Node has a reference on Head pointer to first sentinel Node. I get this idea from Herb Sutter in CppCon video 2016 43:00. In video he talked about unique pointers but I give example with raw pointers, it may be become a little bit confusing.
推荐答案
Node::list_first_node_ptr
是参考.它并不关心被引用对象的 value ,只是被引用对象 itself 实际上存在.由于构造Node::list_first_node_ptr
时肯定会存在List::first_node_ptr
,因此这是合法代码.
Node::list_first_node_ptr
is a reference. It doesn't care about the value of the referenced object, just that the referenced object itself actually exists. Since List::first_node_ptr
is guaranteed to exist when Node::list_first_node_ptr
is constructed, this is legal code.
用另一种方式表达;引用永远不能为空,但是它可以引用为空的指针.
To phrase it another way; a reference can never be null, but it can reference a pointer that is null.
但是,值得注意的是,在Node
完成构造之前,List::first_node_ptr
不会指向有效的对象.这意味着在Node
构造函数完成之前,您不能取消引用List::first_node_ptr
或Node::list_first_node_ptr
.
It's worth noting, though, that List::first_node_ptr
will not point to a valid object until Node
has finished constructing. This means you can't dereference List::first_node_ptr
or Node::list_first_node_ptr
until the Node
constructor has finished.
这篇关于指向未初始化数据成员的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!