Issue
This Content is from Stack Overflow. Question asked by Martin Perry
I have a large codebase that uses std::vector
as data storage for numbers. However, now I need to add support for raw data views, due to external C library that returns raw array. Due to performance reasons, I dont want to copy data to std::vector
.
I was thinking to use std::span from C++20 and create my own storage class like this:
template <typename T>
class DataStorage {
private:
std::vector<T> data;
public:
std::span<T> view;
DataStorage(const std::vector<T>& d) :
data(d),
view(data) {
}
DataStorage(T* d) :
data(),
view(d) {
}
//other ctors
//and methods
}
std::vector<int> vect{ 10, 20, 30 };
DataStorage<int> data(vect);
int value = data.view[1];
To read from data, view will be used. If data are passed via vector, DataStorage
clas will own them. If I pass data via raw pointer (or with some flag), DataStorage
will create only view. Is this a valid design?
Solution
This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.
This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.