简体   繁体   中英

Declare a vector in a function call and pass it by reference

I'd like to declare a vector this way:

myFunction(new std::vector<stuff>{});

With the vector passed as a reference:

void myFunction(const std::vector<stuff> &myVec);

You don't need to new the argument (which in any case returns a pointer, not an lvalue). You can simply pass a temporary:

myFunction(std::vector<stuff>{});

A temporary can bind to a const lvalue reference.

If the parameter is optional, you can simply declare the function as

void myFunction(const std::vector<stuff>& myVec = std::vector<stuff>{});

Then, you can call it like myFunction() when the default argument is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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