Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. A pointer to a class that contains pointers
Qt 6.11 is out! See what's new in the release blog

A pointer to a class that contains pointers

Scheduled Pinned Locked Moved C++ Gurus
3 Posts 3 Posters 1.9k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    karim24
    wrote on last edited by
    #1

    hi i have a class that contains pointers,the class iherits nothing
    @class MyClass
    {
    public:
    MyClass();
    ~MyClass();

    private:
    //i have pointers here
    };
    MyClass::~MyClass()
    {
    qDebug()<<"destroyed..";
    }
    @

    now i have to use this class as a pointer in vector like this:
    @QVector<MyClass*> classes;
    //push some classes in here but
    //when i remove an element
    classes.remove(index);
    //the destructor doesn't get called,and i think that is the true definition of memory leak@

    so how do i make it call the destructor

    1 Reply Last reply
    0
    • C Offline
      C Offline
      chris17
      wrote on last edited by
      #2

      remove only removes the pointer from the vector, but does not delete the object itself, so you need to delete the object when removing it.

      @MyClass *class=classes.at(index);
      classes.remove(index);
      delete class;@

      1 Reply Last reply
      0
      • G Offline
        G Offline
        gvanvoor
        wrote on last edited by
        #3

        If you don't want to explicitly call delete, you could use a vector of shared pointers instead of using raw pointers in the vector.
        Unless you use said shared pointer you should implement the assignment operator and copy-constructor.

        Reason:
        @MyClass instance1;
        {
        MyClass instance2 = instance1;
        }
        // at this point the private pointers in instance1 have been deleted.
        @

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved