Why separate variable definition and initialization in C++?

前端 未结 8 1525
心在旅途
心在旅途 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 16:12

    Object someObject;
    someObject = getTheObject();
    

    This uses the assignment operator.

    Object someObject = getTheObject();
    

    This uses the copy constructor.

    Apart from that, your suggested changes are equivalent, and you should implement them. The copy ctor/assignment operator difference is expected to produce the same result, this is not enforced by the language though.

    I see no valid reason to split up declaration and assignment like the original code does - even though for all practical purposes it doesn't introduce overhead (except for the object)

提交回复
热议问题