How to cheaply assign C-style array to std::vector?

后端 未结 4 1412
[愿得一人]
[愿得一人] 2020-12-01 16:13

Currently I do the following:

// float *c_array = new float[1024];

void Foo::foo(float *c_array, size_t c_array_size) {
  //std::vector cpp_arr         


        
4条回答
  •  隐瞒了意图╮
    2020-12-01 16:36

    The current std::vector doesn't provide any capability or interface to take ownership of previously allocated storage. Presumably it would be too easy to pass a stack address in by accident, allowing more problems than it solved.

    If you want to avoid copying into a vector, you'll either need to use vectors through your entire call chain, or do it the C way with float[] the entire time. You can't mix them. You can guaranteed that &vec[0] will be equivalent to the C-array though, fully contiguous, so using vector in the whole program may be feasible.

提交回复
热议问题