简体   繁体   中英

Use std::vector<T> or make_unique<T[]> to pass pointer to C code

I have a need to get a dynamic array of T, which to see C code I need to interface with is T*.

Should I use a std::vector, then reserve enough count and pass the ::data() pointer or should I use std::make_unique and pass that.

I'm on C++14.

Both will work, and in most cases it is a matter of personal preference. It mostly depends on however the array or vector is used before and after the C API call.

If you already have a vector , or will need the data in a vector afterwards, just use resize ( not reserve ) and go with it. No need to create a new array and copy data to/from it.

But if you only need the data locally and in your algorithm it is not needed to change its length, I would say go with a unique<T[]> , as it would more clearly express your intent for a fixed size array.

Irrespective of the container used to house data, eg vector or T[], the question of using std::unique_ptr is an unrelated question of ownership. The latter question is the more important one, as it is one of correctness rather than performance.

If you intend to transfer sole ownership of the pointer to the receiver function, then std::unique_ptr is a good way to do that. If you do not intend to relinquish ownership of the pointer after the call, then you cannot use std::unique_ptr.

Herb Sutter has a good place to start

https://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/

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