Wrap existing memory with const std::vector?

后端 未结 1 677
孤城傲影
孤城傲影 2021-02-19 13:43

OK, so I recently learned that (a) std::vector uses contiguous memory by definition/standard, and thus (b) &(v[0]) is the address of that contiguous block of memory, which y

1条回答
  •  囚心锁ツ
    2021-02-19 14:49

    You can try reference-logic storing introduced in C++11 with std::reference_wrapper<>:

    SomeClass cary[100];
    // ...
    std::vector> cv;
    cv.push_back(cary[i]);   // no object copying is done, reference wrapper is stored
    

    Or without C11, you can create a specialization of such template class for bytes - char. Then for the constructor from char* C-array you can use ::memcpy: which unfortunately will then use twice as much memory.

    ::memcpy(&v[0], c_arr, n);
    

    Something like this:

    template  class MyVector : public std::vector {
    };
    
    template <> class MyVector : public std::vector {
        public:
        MyVector(char* carr, size_t n) : std::vector(n) {
            ::memcpy(&operator[](0), carr, n);
        }
    };
    

    What I would recommend - replace all C-arrays to vectors where possible, then no extra copying will be needed.

    0 讨论(0)
提交回复
热议问题