这两个表达式是否都相同:“ CTest cTest(t);” “ CTest cTest = t;”在C ++中?效率不同吗?

问题描述 投票:0回答:1

作为主题,相关代码在下面列出。您可以在https://godbolt.org/z/bcf8js上进行检查。

毫无疑问,EntityId_t c_SEDSubscribe(ENTITYID_SEDP_BUILTIN_PUBLICATIONS_READER);调用了the user defined constructor EntityId_t(int id),而我认为EntityId_t c_SEDPPubWriter = ENTITYID_SEDP_BUILTIN_PUBLICATIONS_WRITER;应该调用用户定义的构造函数EntityId_t(int id)和移动赋值运算符,但是由于终止输出,不是这种情况。换句话说,我认为ENTITYID_SEDP_BUILTIN_PUBLICATIONS_WRITER调用用户定义的构造函数EntityId_t(int id)来生成一个临时对象。由于它是一个右值(临时对象),所以complier然后调用运动分配操作。我在哪里错?谢谢您对此问题的帮助。

    #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);
    }
c++ c++11 constructor c++17 move-semantics
1个回答
0
投票

它们是等效的,如果允许从右侧进行隐式转换。如果不是,则ClassName var = foo;格式将导致编译时错误。

#include <cstddef>

class Example {
public:
    Example(int) {}
    explicit Example(std::nullptr_t) {}
};

int main() {
    Example a{0};
    Example b = 0; // Same thing, by implicit conversion.

    Example c{nullptr};
    // Example d = nullptr; // Disallowed; nullptr_t constructor is marked explicit.
}
© www.soinside.com 2019 - 2024. All rights reserved.