vendredi 5 juin 2020

Are these two expresions all the same:"CTest cTest(t);" "CTest cTest=t;" in C++? Only different in efficiency?

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

There is no doubt that EntityId_t c_SEDSubscribe(ENTITYID_SEDP_BUILTIN_PUBLICATIONS_READER); calls the user defined constructor EntityId_t(int id) whereas 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. In another word, I think ENTITYID_SEDP_BUILTIN_PUBLICATIONS_WRITER calls the user defined constructor EntityId_t(int id) to produce a temporary object.Since it's a rvalue(temporary object), complier then calls the movement assigment operation.Where am i wrong? 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(ENTITYID_SEDP_BUILTIN_PUBLICATIONS_READER);
    }

Aucun commentaire:

Enregistrer un commentaire