vendredi 23 mars 2018

Direct access to unique class data member

I have a class with a unique public data member which is a built-in type:

class foo {
public:
    int data;

    foo(int dataIn) : data(dataIn) {}
    virtual ~foo() {}

    // Some other class methods
protected:
    // Some internal helper class methods
};

In an other class, I would like to use memcpy method:

template<typename T>class bar {
protected:
    T data;
public:
    bar() {}
    virtual ~bar() {}

    void write(unsigned char* readBuff, const std::size_t &readSize) {
        // Some stuff
        std::memcpy(readBuff, &(this->data), readSize);
        // Some stuff
    }
};

The idea would be bar to be usable when T is a built-in type or an instance of foo.

But is T is foo and therefore data in bar a foo instance, am I insured that reading from the element pointed by &(this->data) will be data in foo?

When I run this:

foo x(12);
std::cout << sizeof(foo);

I get 4, so foo seems to be exactly the size of an int, so I would naturally think that directly reading/writing to x even without specifying x.data would write to data. Is it true?

I need to be C++11-compatible.

Aucun commentaire:

Enregistrer un commentaire