Object is already initialized on declaration?

后端 未结 5 616
孤城傲影
孤城傲影 2021-02-04 08:13

I\'m trying to understand something in C++. Basically I have this:

class SomeClass {
    public:
        SomeClass();
    private:
        int x;
};

SomeClass::         


        
5条回答
  •  梦毁少年i
    2021-02-04 08:59

    When you declare a variable (without extern) in a function scope (e.g. in main) you also defined the variable. The variable comes into existence at the point at which the declaration is reached and goes out of existence when the end of its scope (in this case the end of the function main) is reached.

    When an object is brought into existence, if it has a user-declared constructor then one of its constructors is used to initialize it. Similary, if it has a user-declared destructor, this is used when the object goes out of scope to perform any required clean up actions at the point at which it goes out of scope. This is different from languages that have finalizers that may or may not run and certainly not at a deterministic point of time. It is more like using / IDisposable.

    A new expression is used in C++ to dynamically create an object. It is usually used where the life time of the object cannot be bound to a particular scope. For example, when it must continue to exist after the function that creates it completes. It is also used where the exact type of the object to be created is now known at compiler time, e.g. in a factory function. Dynamically create objects can often be avoided in many instances where they are commonly used in languages such as Java and C#.

    When an object is created with new, it must at some point be destroyed through a delete expression. To make sure that programmers don't forget to do this it is common to employ some sort of smart pointer object to manage this automatically, e.g. a shared_ptr from tr1 or boost.

提交回复
热议问题