I am a beginner in C++, and got confused about the initialization of const pointers declared in headers. 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:
/* 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? And to the extent each new call needs a dedicated delete call, can I delete my pointer tmpA immediately after the line *myPtrA = *a; without risk of losing the content pointed by myPtrA?
Thank you in advance for your time (and pardon my English ;) )
qroh
*myPtrA = *tmpA;
Is this the good way to initialize my const pointer myPtrA?
No. You haven't initialized myPtrA
at all. It was default-initialized and therefore has indeterminate value. Dereferencing the pointer with indeterminate value ( *myPtrA
) has undefined behaviour.
can I delete my pointer tmpA immediately after the line *myPtrA = *a; without risk of losing the content pointed by myPtrA?
Yes, it is safe. The object pointed by myPtrA
is copy (by assignment) of the one pointed by 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. 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.