C++ vs Java constructors

前端 未结 14 2714
一个人的身影
一个人的身影 2021-02-09 20:31

According to John C. Mitchell - Concepts in programming languages,

[...] Java guarantees that a constructor is called whenever an object is created.

14条回答
  •  温柔的废话
    2021-02-09 21:32

    As far as I remember, Meyers in his "Effective C++" says, that the object is ONLY created when the control flow has reached his constructor's end. Otherwise it is not an object. Whenever you want to mistreat some raw memory for an actual object, you can do this:

    class SomeClass
    {
       int Foo, int Bar;
    };
    
    SomeClass* createButNotConstruct()
    {
       char * ptrMem = new char[ sizeof(SomeClass) ];
       return reinterpret_cast(ptrMem);
    }
    

    You won't hit any constructors here, but you may think, that you are operating a newly created object (and have a great time debugging it);

提交回复
热议问题