Wrap existing memory with const std::vector?

后端 未结 1 680
孤城傲影
孤城傲影 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<std::reference_wrapper<SomeClass>> 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 <typename T> class MyVector : public std::vector<T> {
    };
    
    template <> class MyVector<char> : public std::vector<char> {
        public:
        MyVector<char>(char* carr, size_t n) : std::vector<char>(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)
提交回复
热议问题