Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

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

/* 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 ?

question from:https://stackoverflow.com/questions/8660025/why-doesnt-c-require-a-new-statement-to-initialize-stdvector

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...