Object is already initialized on declaration?

后端 未结 5 624
孤城傲影
孤城傲影 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条回答
  •  渐次进展
    2021-02-04 08:52

    In your case, sc is allocated on the stack, using the default constructor for SomeClass. Since it is on the stack, the instance will be destructed upon returning from the function. (This would be more impressive if you instantiated SomeClass sc within a function called from main--the memory allocated for sc would be unallocated upon the return to main.)

    The new keyword, instead of allocating memory on the run-time stack, allocates the memory on the heap. Since C++ has no automatic garbage collection, you (the programmer) are responsible for unallocating any memory you allocate on the heap (using the delete keyword), in order to avoid memory leaks.

提交回复
热议问题