Differences Between Python and C++ Constructors

前端 未结 4 2165
攒了一身酷
攒了一身酷 2021-02-19 09:07

I\'ve been learning more about Python recently, and as I was going through the excellent Dive into Python the author noted here that the __init__ method is not tech

4条回答
  •  情深已故
    2021-02-19 09:33

    In Python an object is created, by __new__, and that sort of generic default object is modified by __init__. And __init__ is just an ordinary method. In particular it can be called virtually, and calling methods from __init__ calls them virtually.

    In C++ raw memory for an object is allocated in some way, statically, or on a call stack, or dynamically via operator new, or as part of another object. Then the constructor for the type that you're instantiating initializes the raw memory to suitable values. A constructor for a given class automatically calls constructors of base classes and members, so construction is guaranteed a "bottom up" construction, making the parts first.

    C++ adds language support for two specially important aspects of the idea of construction from parts:

    • If a constructor fails (by throwing an exception), then parts that have been successfully constructed are destroyed, automatically, and memory for the object is deallocated, automatically.
    • During execution of the body of a constructor of a type T the object is of type T, so calls to virtual methods will resolve as if the object is of type T (which it is, at this point), where T can be a base class of the class you instantiated.

    The first point means that with a properly designed C++ class, when you have an object at hand it's guaranteed usable as-is. If the construction fails then you simply don't end up with an object at hand.

    Also, the rules of C++ are designed to ensure that for every object of most derived class T there is one and only one T constructor call. I used to call it the single constructor call guarantee. It's not specified as such any place in the standard, and you can foil it by using very low level facilities of the language, but it's there, it's what the detailed rules of the standard are designed to accomplish (it's much the same as you won't find any single rule about semicolon-termination of statements, yet all the myriad syntax rules for various statements conspire to yield a simple high level rule).

    The single constructor call guarantee, and the automatic cleanup guarantee, and the changing type of an object as constructors of base classes are exectued, are perhaps the three most important differences from a Python object construction.

    There's much much more to be said, but I think these are the most important ideas.

    Cheers & hth.,

提交回复
热议问题