lundi 27 mars 2017

Wrapping binary buffers - possible without extraneous moving/copying?

Fair warning, I am a C++ novice so some or all of my assumptions might be faulty.

Consider the following:

#include <cstddef>
#include <cstdio>

template <typename T>
class StaticData {
private:
    const T* data = nullptr;
    std::size_t size;
public:
    StaticData(const T* data, std::size_t size) : data(data), size(size) { }
    const T* GetData() {
        return this->data;
    }
    std::size_t GetSize() {
        return this->size;
    }
};

const unsigned char foo[] = { 0x66, 0x6F, 0x6F };
// Possible to initialize this class with data directly?
StaticData<unsigned char> SDFoo = StaticData<unsigned char>(foo, sizeof(foo));

int main() {
    std::printf("%p (%lu)\n", foo, sizeof(foo));
    std::printf("%p (%lu)\n", SDFoo.GetData(), SDFoo.GetSize());
}

With this code, I am wrapping foo in an (incomplete) class that contains the data and its value. I have no interest in modifying the contained data, I simply want a safe wrapper for it that has its size always available. I first tried std::array, but it has the unfortunate side effect of making the size a part of its type, and I cannot put arrays of different sizes inside a container such as an std::unordered_map.

The only problem with this approach is that foo is still hanging out in the global scope. For safety's sake, I would much rather the container class SDFoo being the only thing visible (as Foo perhaps). However, I cannot figure out a way to get rid of foo without introducing unnecessary moving or copying of the entire buffer at static initialization time.

Any ideas?

EDIT: To be clear, I was wondering if there was a way to get rid of the extra foo variable somehow.

Aucun commentaire:

Enregistrer un commentaire