c++ - Cast of pointer to vector of different types -


i have function requires pointer vector of type uint16_t. function fills vector data. have object should hold data in form of vector of type uint8_t. code looks following:

void fill1(vector<uint16_t> *data); void fill2(vector<uint64_t> *data);  class object {     uint32_t data_depth;     vector<uint8_t> data; }  object object1; object1.data_depth = 16; fill1((vector<uint16_t>*) &object1.data);  object object2; object2.data_depth = 64; fill2(vector<uint64_t>*) &object2.data);  // somewhere later in code if (object1.data_depth == 16)    vector<uin16_t> * v = (vector<uint16_t>)(&objec1.data); 

is save way of pointer conversion of vector of different types?

you this:

template <typename t> void fill(vector<unsigned char>& data) {     assert(data.size() % sizeof(t) == 0);      t* preinterpreted = reinterpret_cast<t*>(&data[0]);     size_t count = data.size() / sizeof(t);      // stuff array of reinterpreted values }  class object {     uint32_t data_depth;     vector<unsigned char> data; }  object object; fill<uint16_t>(object.data); 

naturally, unsafe code wouldn't unless know trade-offs here.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -