Why doesn't C++ require a "new" statement to initialize std::vector?

ash picture ash · Dec 28, 2011 · Viewed 87.2k times · Source
/* bar.h */
class bar{
    /* standard stuff omitted */
    std::vector<my_obj*> foo;
};

/* bar.cpp */
bar::bar(){ 
    // foo = new std::vector<my_obj*>(); <-- why don't I need this line??
    foo.push_back(new my_obj());
}

Why does this code work even though we didn't assign foo a new instance of std::vector ?

Answer

Nicol Bolas picture Nicol Bolas · Dec 28, 2011

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.