C++ pointer to class

后端 未结 6 1590
小鲜肉
小鲜肉 2021-01-30 23:11

Can anyone tell me what the difference is between:

Display *disp = new Display();

and

Display *disp;
disp = new Display();
         


        
6条回答
  •  时光说笑
    2021-01-30 23:57

    Display *disp = new Display();
    

    This line of code create a variable of type Display* and initializes it with the address of a newly created object.

    Display *disp;        // (1)
    disp = new Display(); // (2)
    

    First line of code simply declares a variable of type Display*. Depending on your compiler settings - the pointer may or may not be initialized. Basically, it should be treated as an invalid pointer, that doesn't necessary point to NULL.

    Second line assigns address of a newly created object to the pointer.

    The outcome of both code snippets will be the same.

    With optimizations enabled, any compiler should generate the same assembly for both of them. With optimizations disabled, and with some debug code generation - both snippets might generate totally different code - in the second case, the pointer would first be initialized with a value used by compiler for uninitialized pointers (something like 0xDEADBEEF, or 0xEFEFEFEF - and easily recognizable pattern). In the first snippet - the pointer should always be initialized to the address of the object, regardless of the settings. Note, that this is compiler-dependent - some compilers might do as I say, some may do somthing completely different.

提交回复
热议问题