自动更新struct中的指针值

Update pointer value in struct automatically

本文关键字:指针 struct 更新      更新时间:2023-10-16

是否有可能在内存分配后自动更新结构中的指针值?请看看代码

struct S {void *ptr;};
void *p;
struct S ST= {p};
int main() {
    p = new int;
    void* b = ST.ptr; // b should be the same as p
    return 0;
}

您可以简单地持有间接:

c++:

struct S
{
    void*&  ptr; // ptr is now a reference to a pointer. Drawback: Has to be initialized.
};

可以这样使用:

S s = {p};

但是引用作为成员是一个有争议的话题。在这种情况下,另一种间接方式可能更好:

C:

也许代码片段中的new只是为了说明目的,而您使用的是C(代码中精心设计的类型说明符支持该参数)。

struct S
{
    void**  ptr; // ptr is now a pointer to a pointer. Drawback: Can be zero.
};

在本例中,您使用它应该引用的指针的地址初始化ptr:

struct S s = {&p}; // I don't know about list-initialization in C, so i'll stick to this

随后,当解引用它时,您将得到p的左值。

关于引用和指针的区别,请阅读这篇文章。

别忘了智能指针。也许共享所有权就是你想要的。