简体   繁体   中英

Default initialization for a class pointer

I have seen the following construction in many code reviews:

ClassX *pObj;
ClassX  obj;

pObj = &obj; //obj is not used in the rest of the code

Is the line below only used for initialization purposes?

pObj = &obj;

Why is it not initialized to NULL ?

pObj = &obj; here pObj is pointer and it is pointing to obj .

Like below,

在此处输入图片说明

Note : Only for illustration purpose I have chosen address of obj , pObj as 0x1000,0x2000 respectively.

Why they do not initialize to NULL.

pObj can be initialized to NULL but eventually overwritten by pObj = &obj and hence no side effect occurs. But access to pObj before assignment causes UB.

pObj is a pointer to a properly initialised instance that can be used by the rest of the function or any called functions. NULL would mean there is no instance, a very different thing.

But why would you do this? One answer is that the rest of the code uses pointers and the author feels happier using pObj than using &obj.

Another may be that the pointer later gets assigned to a real object "usually". You didn't show us the later code so we have to speculate (or downvote). Perhaps the author thinks that having a valid temporary is less prone to crashes than having a null ptr if the assignment fails and the later code that uses the pointer is allowed to run, but this really is lazy programming, paying to initialise an object you never intend to use. If the real object is dynamically allocated, then the pointer might be valid outside the scope of this code, but the default instance would not be.

Sometimes construction/copy/move of objects is costly or impossible; thus pointer ClassX* pObj; can serve as a tool to quickly change target - as copying pointers is simple and cheap overall.

Say, in a loop pObj is frequently used and sometimes you need it to point to one object, then to another, and carryover it to next iterations. Or you have some complex rules that determine to which variable the pointer points to.

If one could've simply used obj instead of the pObj in the method without any issues - then it is simply poor coding practices to use pObj . Some might use it to save & when passing pointers... but that's barely an excuse. Regardless, I don't see much harm except for clutter.

Or they simply copied the code from elsewhere (that was also copied from another place...) without dwelling on it much as to why it is written in this way.

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.

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