I\'m trying to understand something in C++. Basically I have this:
class SomeClass {
public:
SomeClass();
private:
int x;
};
SomeClass::
Some other answers are basically telling you "sc is allocated on the stack, new allocates the object on the heap". I prefer not to think about it in this way as it conflates implementation details (stack/heap) with the semantics of the code. Since you are used to the way C# does things I think it also creates ambiguities. Instead, the way I prefer to think about it is the way the C++ standard describes it:
sc is variable of type SomeClass, declared at block scope (ie, the braces that make up the main function). This is called a local variable. Because it is not declared static
or extern
, this makes it have automatic storage duration. What this means is that whenever the line SomeClass sc;
is executed, the variable will be initialized (by running its constructor), and when the variable goes out of scope by exiting the block, it will be destroyed (by running its destructor - since you do not have one and your object is plain old data, nothing will be done).
Earlier I said "Because it is not declared static
or extern
", if you had declared it as such it would have static storage duration. It would be initialized before program startup (technically at block scope it would be initialized at first use), and destroyed after program termination.
When using new
to create an object, you create an object with dynamic storage duration. This object will be initialized when you call new
, and will only be destroyed if you call delete
on it. In order to call delete, you need to maintain a reference to it, and call delete when you are finished using the object. Well written C++ code typically does not use this type of storage duration very much, instead you will typically place value objects into containers (eg. std::vector
), which manage the lifetime of contained values. The container variable itself can go in static storage or automatic storage.
Hope this helps disambiguate things a little, without piling on too many new terms so as to confuse you.