Because C++ is not C#/Java.
std::vector<my_obj*> foo;
This is a definition of an object, not a reference as in C#/Java. An object is a living instance of a type.
new std::vector<my_obj*>()
This expression returns a pointer. It returns a std::vector<my_obj*>*
, which is not the same type as foo
(the *
at the end is what makes them different). foo
is an object, std::vector<my_obj*>*
is a pointer to an object.
Objects (rather than pointers or references) have specific lifetimes. If you create a pointer to an object with new
, the lifetime of the object pointed to will be until you explicitly call delete
. If you create an object as a member of another object, then that inner object's lifetime will (more or less) mirror the outer object's lifetime. If you create an object on the stack (a parameter or variable at function scope), then its lifetime is the current scope of that variable name.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…