gpt4 book ai didi

c++ - 是否必须初始化成员才能获取其地址?

转载 作者:IT老高 更新时间:2023-10-28 21:35:56 26 4
gpt4 key购买 nike

我可以在初始化成员之前初始化指向数据成员的指针吗?换句话说,这是有效的 C++ 吗?

#include <string>

class Klass {
public:
Klass()
: ptr_str{&str}
, str{}
{}
private:
std::string *ptr_str;
std::string str;
};

this问题和我的类似,但是那里的顺序是正确的,答案是

I'd advise against coding like this in case someone changes the order of the members in your class.

这似乎意味着颠倒订单是非法的,但我不能确定。

最佳答案

Does a member have to be initialized to take its address?

没有。

Can I initialize a pointer to a data member before initializing the member? In other words, is this valid C++?

是的。是的。

一元 & 的操作数不需要初始化是没有限制的。一元&运算符的规范中有一个例子:

int a;
int* p1 = &a;

这里a的值是不确定的,指向它就可以了。

该示例未演示的是在其生命周期开始之前指向一个对象,这就是您的示例中发生的情况。如果存储空间被占用,使用一个指向对象之前和之后的对象的指针是明确允许的。标准草案说:

[basic.life] Before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that represents the address of the storage location where the object will be or was located may be used but only in limited ways ...

该规则继续列出如何限制使用。凭常识就能过得去。简而言之,您可以像对待 void* 一样对待它,除了违反这些限制是 UB 而不是格式错误。引用也有类似的规则。

对计算非静态成员的地址也有限制。标准草案说:

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

Klass的构造函数中,Klass的构造已经开始,销毁还没有完成,所以满足上述规则。


附:您的类是可复制的,但拷贝将具有指向另一个实例成员的指针。考虑这对你的类(class)是否有意义。如果没有,您将需要实现自定义复制和移动构造函数和赋值运算符。像这样的自引用很少见,您可能需要自定义定义,但不需要自定义析构函数,因此它是五(或三)规则的异常(exception)。

P.P.S 如果您的意图是指向成员之一,并且除了成员之外没有其他对象,那么您可能希望使用指向成员的指针而不是指向对象的指针。

关于c++ - 是否必须初始化成员才能获取其地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56078944/

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