简体   繁体   中英

Why is the copy constructor of this template class not getting called?

The copy constructor never gets called (I'm using g++ with -std=c++11):
pointers.cpp:

#include <iostream>

template <typename T>
class SharedPtr
{
private:
    int *m_Count;
    T *m_Ptr;

public:
    SharedPtr(T *ptr = nullptr)
        : m_Count(new int), m_Ptr(ptr)
    {
        *m_Count = 1;
    }

    SharedPtr(const SharedPtr &other)
        : m_Count(other.m_Count), m_Ptr(other.m_Ptr)
    {
        std::cout << "Copied: " << *m_Count << std::endl;
        (*m_Count)++;
    }

    ~SharedPtr()
    {
        (*m_Count)--;
        if (*m_Count == 0)
        {
            delete m_Ptr;
            delete m_Count;
        }
    }

    T &operator*()
    {
        return *m_Ptr;
    }
};

main.cpp:

#include "pointers.cpp"
#include <iostream>

class Entity
{
public:
    Entity()
    {
        std::cout << "Entity created!" << std::endl;
    }
    ~Entity()
    {
        std::cout << "Entity destroyed!" << std::endl;
    }
};

int main(int argc, char *argv[])
{
    {
        SharedPtr<Entity> e0;
        std::cin.get();
        {
            SharedPtr<Entity> sharedEntity = new Entity();
            std::cin.get();
            e0 = sharedEntity;
            std::cin.get();
        }
        std::cin.get();
    }

    std::cin.get();
}

I looked at other similar questions asked here, but none of them worked. The copy constructor should be ClassName(const ClassName &other) , right?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam lacinia mattis arcu, vitae interdum leo. Praesent viverra, tortor a tincidunt ullamcorper, arcu urna finibus enim, congue dignissim tortor quam ut dui. Ut eleifend suscipit ligula sagittis consequat. Integer semper orci eu metus mollis sodales. Fusce sollicitudin elementum nisl, non congue odio lobortis non. Duis tempus tristique nisi nec tempor. Sed in ullamcorper nisi. Suspendisse id suscipit magna, eu pellentesque ligula. Nullam aliquam pretium tellus, eget venenatis eros pharetra finibus.

None of the code in main() calls the copy contructor of SharedPtr :

  • SharedPtr<Entity> e0; calls SharedPtr(T *ptr = nullptr)
  • SharedPtr<Entity> sharedEntity = new Entity(); calls SharedPtr(T *ptr = nullptr)
  • e0 = sharedEntity; calls operator=() which is not defined in your SharedPtr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM