简体   繁体   English

初始化指向结构C的const指针

[英]Initializing a const pointer to a structure c++

I am a beginner in C++, and got confused about the initialization of const pointers declared in headers. 我是C ++的初学者,对在标头中声明的const指针的初始化感到困惑。 To give but one example, I have in my header a structure and a class like: 仅举一个例子,我的标头中有一个结构和一个类似的类:

/* header file.h */
typedef struct A{ ... } A;

class myClass{
    protected:
        A *const myPtrA;
}

And would like to instantiate the content of myPtrA, for instance in a constructor, knowing that A is a quite complicated structure composed of substructures, and needs to be dynamically instantiated: 并且想实例化myPtrA的内容,例如在构造函数中,知道A是由子结构组成的相当复杂的结构,并且需要动态实例化:

/* source file.cpp */
#include file.h

myClass::myClass() {
   A *tmpA = new A;
   *myPtrA = *tmpA;
}

Is this the good way to initialize my const pointer myPtrA? 这是初始化我的const指针myPtrA的好方法吗? And to the extent each new call needs a dedicated delete call, can I delete my pointer tmpA immediately after the line *myPtrA = *a; 并且在每个新调用都需要专用的删除调用的范围内,我可以在* myPtrA = * a行之后立即删除指针tmpA吗? without risk of losing the content pointed by myPtrA? 不会丢失myPtrA指出的内容的风险?

Thank you in advance for your time (and pardon my English ;) ) 在此先感谢您的宝贵时间(请原谅我的英语;))

qroh ro

 *myPtrA = *tmpA; 

Is this the good way to initialize my const pointer myPtrA? 这是初始化我的const指针myPtrA的好方法吗?

No. You haven't initialized myPtrA at all. 不。您根本没有初始化myPtrA It was default-initialized and therefore has indeterminate value. 它是默认初始化的,因此具有不确定的值。 Dereferencing the pointer with indeterminate value ( *myPtrA ) has undefined behaviour. 用不确定的值( *myPtrA*myPtrA引用指针具有未定义的行为。

can I delete my pointer tmpA immediately after the line *myPtrA = *a; 我可以在* myPtrA = * a行之后立即删除指针tmpA吗? without risk of losing the content pointed by myPtrA? 不会丢失myPtrA指出的内容的风险?

Yes, it is safe. 是的,这很安全。 The object pointed by myPtrA is copy (by assignment) of the one pointed by tmpA . 通过指向的对象myPtrA是一个通过指出的拷贝(通过分配) tmpA However, it is completely pointless to allocate a dynamic object, copy it and then detroy it in the first place, when you could simply create/modify the copy directly. 但是,分配动态对象,先将其复制然后销毁它完全是没有意义的,因为您可以直接直接创建/修改副本。

Here is an example of how to correctly initialize the member pointer: 这是如何正确初始化成员指针的示例:

class myClass{
    protected:
        A *const myPtrA = new A;
};

PS. PS。 While it is useful to learn how to do this, you should hardly ever manage memory manually in actual programs. 虽然学习如何执行此操作很有用,但几乎不应在实际程序中手动管理内存。 Instead use RAII containers such as std::unique_ptr . 而是使用RAII容器,例如std::unique_ptr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM