Why separate variable definition and initialization in C++?

前端 未结 8 1492
心在旅途
心在旅途 2021-02-18 15:22

I\'m currently working on some quite old C++ code and often find things like

int i;
i = 42;

or

Object* someObject = NULL;
someO         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-18 15:54

    Why separate variable definition and initialization in C++?

    You haven't separated definition and initialization. You have just assigned the variable/object (to some particular) value in your code snippet. So the title is misleading.

    Object someObject;
    someObject = getTheObject();
    

    is quite different from Object someObject = getTheObject();

    someObject = getTheObject(); invokes the assignment operator of Object class whereas in Object someObject = getTheObject(); copy constructor of the class gets invoked. This is also known by the name copy initialization

    A good compiler might generate the same code in case of int i; i = 42; and int i =42. There won't be much of an overhead.

    BTW I always prefer int i = 42 to int i; i=42 and

    Object someObject = getTheObject(); to

    Object someObject; someObject = getTheObject();

    P.S : int i = 42 defines and initializes i whereas int i; i=42 defines i and then assigns 42 to it.

提交回复
热议问题