Should Local Variable Initialisation Be Mandatory?

前端 未结 17 2453
忘掉有多难
忘掉有多难 2021-02-14 01:26

The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still se

17条回答
  •  离开以前
    2021-02-14 02:08

    This pertains to C++ only, but there is a definite distinction between the two methods. Let's assume you have a class MyStuff, and you want to initialize it by another class. You could do something like:

    // Initialize MyStuff instance y
    // ...
    MyStuff x = y;
    // ...
    

    What this actually does is call the copy constructor of x. It's the same as:

    MyStuff x(y);
    

    This is different than this code:

    MyStuff x; // This calls the MyStuff default constructor.
    x = y; // This calls the MyStuff assignment operator.
    

    Of course, completely different code is called when copy constructing vs. default constructing + assigning. Also, a single call to the copy constructor is likely to be more efficient than construction followed by assignment.

提交回复
热议问题