Dynamic memory question

What is the diff between pscobject = new _pscmain; and
_pscmain * pscobject ?

For dynamic memory we need to deal with pointer. So to initinialize pointer is
_pscmain * pscobject . Then what for pscobject = new _pscmain;?
Last edited on
 
_pscmain * pscobject


Declares a pointer with the name pscobject, which will point to a _pscmain object. It is uninitialized.

 
_pscmain *pscobject = nullptr;


Is somewhat safer as you can do:

1
2
3
4
5
6
if (pscobject)
{
    // Pointer points to SOMETHING
}
else
    throw "Dayum, uninitialized ptr bro!";


 
pscobject = new _pscmain;


Creates an actual objects and puts the address of that object inside the pscobject pointer. [Think of the pointer as a WORD sized integer that points to a memory cell.].

The safest method is to initialize at declaration.

 
_pscmain *pscobject = new _pscmain;


You now have a valid object. Remember to delete the pointer when you're done. Preferably, use std::unique_ptr or std::shared_ptr.
Understood :)
Topic archived. No new replies allowed.