简体   繁体   English

矢量指针和push_back()

[英]Vector pointer and push_back()

If I have 如果我有

void f(vector<object> *vo) {

}

And I pass the address of a vector to f 我将向量的地址传递给f

vector<object> vo;
f(&vo);

How would I use push_back() to add to the vector? 我如何使用push_back()添加到向量?

Dereference the pointer: 取消引用指针:

(*vo).push_back(object());
vo->push_back(object()); // short-hand

Note this is a basic concept of the language, you may benefit from reading a good book . 请注意,这是该语言的基本概念,您可以从阅读一本好书中受益。


Note this has a glaring shortcoming: 请注意,这有一个明显的缺点:

f(0); // oops, dereferenced null; undefined behavior (crash)

To make your function safe, you need to correctly handle all valid pointer values (yes, null is a valid value). 为了使您的函数安全,您需要正确处理所有有效的指针值(是的,null是一个有效值)。 Either add a check of some kind: 要么添加某种支票:

if (!vo) return;
// or:
if (!vo) throw std::invalid_argument("cannot be null, plz");

Or make your function inherently correct by using a reference: 或者通过使用引用使您的函数本身正确:

void f(vector<object>& vo) // *must* reference a valid object, null is no option
{
    vo.push_back(object()); // no need to dereference, no pointers; a reference
}

Now the onus is on the caller of the function to provide you with a valid reference. 现在,函数的调用者有责任为您提供有效的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM