Thee problem here is to understand if the copy or move constructor was called when initializing a vector by a return object of a function. Checking the mallocs with a profiler shows similar memcopies in both cases. Why?
We have a class of type "message". The class provides a function "data_copy" which returns the contents of the "message" as vector.
There are 2 options that I tried. One is to use directly the copy constructor to initialize a new vector.
std::vector<uint8_t> vector1 ( message.data_copy() );
The second option was to try to avoid the extra copy and do
std::vector<uint8_t> vector1 ( std::move( message.data_copy() ) );
For reference I attach what data_copy() does.
std::vector<uint8_t> message::data_copy(void) const
{
std::vector<uint8_t> d(this->size());
copy_data_to_buffer(d.data());
return d;
}
void message::copy_data_to_buffer(uint8_t* buffer) const
{
DEBUG_LOG("copy_data_to_buffer");
for(const fragment* p = &head; p != nullptr; p = p->next)
{
memcpy(buffer, p->data[0], p->size[0]);
buffer += p->size[0];
if(p->size[1])
{
memcpy(buffer, p->data[1], p->size[1]);
buffer += p->size[1];
}
}
}
Finally, by using a profiler I compare the amount of malloc calls. While one would expect that the move constructor would avoid the extra memcopy in reality they are the same in both cases.
Aucun commentaire:
Enregistrer un commentaire