Why does the copy constructor and copy assignment operator call `memcpy` whereas the movement ctor and movement assignment operator call `memmove`

0

As the subject, the related code is listed below.You could check it on https://godbolt.org/z/mAbmwJ.

I completely understand the differences between memcpy(3) and memmove(3), but I don't understand the reasons lie behind it.The code is quoted from an wellknown open source project, I don't doublt the correctness of the code and the developers must have some reasons to do so. I would be grateful to have some help with this question.

#include<string.h>
#include<iostream>

#define ENTITYID_UNKNOWN 0x00000000
#define ENTITYID_SEDP_BUILTIN_PUBLICATIONS_WRITER  0x000003c2
#define ENTITYID_SEDP_BUILTIN_PUBLICATIONS_READER  0x000003c1

struct EntityId_t
{
    static constexpr unsigned int size = 4;
    char value[size];
    //! Default constructor. Uknown entity.
    EntityId_t(){
        *this = ENTITYID_UNKNOWN;
    }

    EntityId_t(int id)
    {
        int* aux = (int*)(value);
        *aux = id;
         std::cout << "EntityId_t(int id) constructor" << std::endl;
    }

    /*!
     * @brief Copy constructor
     */
    EntityId_t(
            const EntityId_t& id)
    {
        memcpy(value, id.value, size);
        std::cout << "copy constructor" << std::endl;
    }

    EntityId_t& operator =(
            const EntityId_t& id)
    {
        memcpy(value, id.value, size);
        std::cout << "copy operator() constructor" << std::endl;
        return *this;
    }

    /*!
     * @brief Move constructor
     */
    EntityId_t(
            EntityId_t&& id)
    {
        memmove(value, id.value, size);
        std::cout << "move constructor" << std::endl;
    }

    EntityId_t& operator =(
            EntityId_t&& id)
    {
        memmove(value, id.value, size);
        std::cout << "move operator(EntityId_t&&)" << std::endl;
        return *this;
    }
};



int main()
{
    EntityId_t c_SEDPPubWriter = ENTITYID_SEDP_BUILTIN_PUBLICATIONS_WRITER;
    std::cout << "==============================" << std::endl;

    EntityId_t c_SEDSubscribe;
    c_SEDSubscribe = ENTITYID_SEDP_BUILTIN_PUBLICATIONS_READER;
}

Output:

EntityId_t(int id) constructor
==============================
EntityId_t(int id) constructor
move operator(EntityId_t&&)
EntityId_t(int id) constructor
move operator(EntityId_t&&)
c++
c++11
constructor
copy-constructor
move-semantics
asked on Stack Overflow Jun 5, 2020 by John • edited Jun 6, 2020 by John

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0