gpt4 book ai didi

c++ - 在构造函数中使用指向(仍然)未初始化成员的指针是否安全?

转载 作者:行者123 更新时间:2023-11-30 04:17:23 24 4
gpt4 key购买 nike

例如

//somewhere
struct IFace;

struct Base
{
Base(IFace* iface):
f(iface)
{
//will not use iface here
}
private:
IFace* f;
};

struct Data;
struct Implementation
{
private:
friend IFace* factory_create(Data*);
Implementation(Data* data): // ok, it's not private, just some internal
// class not mentioned in public headers
d(data)
{
//will not deref data here
}

private:
Data* d;
};

IFace* factory_create(Data* data)
{
return new Implementation(data);
}


//here
struct Derived: Base
{
Derived():
Base(factory_create(&data)) //using pointer to uninitialized member
{
//will fill data here
}

Data data;
};

在将指向它的指针传递给 factory_create 函数之前,我似乎没有机会创建 data

这段代码安全吗?如果不是,我应该做哪些最小的更改以使其安全?

最佳答案

指针是安全有效的,只要不取消引用就可以使用。将 ponter 值存储在注册表中以供稍后在完全构建时使用是一种相当普遍的做法。

传递 'this' 的类似故事也受到警告,甚至可以用于限制已构建的元素。

[class.cdtor]/3

To form a pointer to (or access the value of) adirect non-static member of an object obj, the construction of objshall have started and its destruction shall not have completed,otherwise the computation of the pointer value (or accessing themember value) results in undefined behavior.

关于c++ - 在构造函数中使用指向(仍然)未初始化成员的指针是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17116040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com