vendredi 5 juin 2020

Question about movement assignment operator

As the subject, the related code is listed below.You could check it on https://godbolt.org/z/wqyon9. I think EntityId_t c_SEDPPubWriter = ENTITYID_SEDP_BUILTIN_PUBLICATIONS_WRITER; should call the user defined constructor EntityId_t(int id) and movement assignment operator, but it's not this case since the terminate output.Could somebody tell the reasons?

In addition, why does the copy constructor and copy assignment operator call memcpy whereas the copy movement constructor and movement assignment memmove.I know the differences between memcpy(3) and memmove(3), but i could understand the reasons lie behind it.The code is quoted from an open source project, i think the code is right 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

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_WRITER;
}

Output:

EntityId_t(int id) constructor
==============================
EntityId_t(int id) constructor
move operator(EntityId_t&&)
EntityId_t(int id) constructor
move operator(EntityId_t&&)

Aucun commentaire:

Enregistrer un commentaire