为什么C ++不需要"new"?语句初始化std :: vector? [英] Why doesn't C++ require a "new" statement to initialize std::vector?

查看:174
本文介绍了为什么C ++不需要"new"?语句初始化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());
}

即使我们没有为foo分配std :: vector的新实例,为什么这段代码也能正常工作?

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

推荐答案

因为C ++不是C#/Java.

Because C++ is not C#/Java.

std::vector<my_obj*> foo;

这是对象的定义,而不是C#/Java中的引用.对象是某种类型的活动实例.

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*>()

此表达式返回一个 pointer .它会返回 std :: vector< my_obj *> * ,该类型与 foo 的类型不同( * 到底是什么使它们与众不同). foo 是一个对象, 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.

对象(而不是指针或引用)具有特定的生存期.如果使用 new 创建指向对象的指针,则所指向的对象的生命周期将一直持续到您明确调用 delete 为止.如果将一个对象创建为另一个对象的成员,则内部对象的生存期将(或多或少)反映外部对象的生存期.如果在堆栈上创建对象(函数范围内的参数或变量),则其生存期就是该变量名称的当前范围.

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.

这篇关于为什么C ++不需要"new"?语句初始化std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆