自动更新struct中的指针值
Update pointer value in struct automatically
是否有可能在内存分配后自动更新结构中的指针值?请看看代码
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
的左值。
关于引用和指针的区别,请阅读这篇文章。
别忘了智能指针。也许共享所有权就是你想要的。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- "typedef"类型名称是否可以像"struct"定义那样声明指向结构的指针?
- sizeof(* struct 指针)是否给你结构的值
- 删除字符串指针在struct中的内存
- 如何使用struct构造函数在结构中初始化指针阵列
- 引用绑定到类型 'struct value_type' 的 null 指针
- 指向struct的指针,包含指向对象的指针,我想调用一个函数
- 如何从采用 int 和 struct 类型的指针的函数中取消引用指针返回的地址?
- 将指向struct的指针强制转换为数组
- 在struct[]中分配char*指针值(结构成员)的最优化方法
- 在类函数中返回Struct指针
- typedef struct 指针进入 JNA
- 将char复制到struct指针char
- 指针函数在类中返回Struct的值
- 初始化Struct指针
- 将指向struct的指针强制转换为数组指针是否有效?
- 自动更新struct中的指针值
- 初始化指向struct语法的指针
- 在c++中初始化指向struct的指针