QList and shared_ptr

What do you think? Is this correct or are there memory leaks?

Source:

#include <QList.h>
#include <boost/shared_ptr.hpp>
#include <iostream>

class A {
private:
    int m_data;
public:
    A(int value=0) { m_data = value; }
    ~A() { std::cout << "destroying A(" << m_data << ")" << std::endl; }
    operator int() const { return m_data; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    QList<boost::shared_ptr<A> > list;
    list.append(boost::shared_ptr<A>(new A(6)));
    std::cout << int(*(list.at(0))) << std::endl;
    return 0;
}

Output:

6
destroying A(6)

Answers


It seems correct. Boost's shared_ptr is a reference counting pointer. Reference counting is able to reclaim memory if there are no circular references between objects. In your case, objects of class A do not reference any other objects. Thus, you can use shared_ptr without worries. Also, the ownership semantics allow shared_ptrs to be used in STL (and Qt) containers.


This code looks perfectly fine.

If you're seeking advice perhaps you could provide more info on the purpose of using shared_ptr with QList, there might be a "Qt" way of doing this without pulling the big guns such as shared_ptr.


It is difficult to suggest anything without knowing why the list of shared_ptrs of A objects exist in the first place.

Take a look at the ownership semantics of smart pointers. Maybe of help to you.

Some other things that can be improved:

1. Use initializer lists in ctor like:

class A {
 private:
   int m_data;
 public:
    A(int value=0) : m_data (value) {}
 // ....

2. int _tmain(int argc, _TCHAR* argv[]) is not a Standard signature;

Use

int main(int argc, char* argv[])

or just:

int main()

If you're not using a smart pointer, you have to delete the list elements by yourself.

Source:

#include <QList.h>
#include <boost/shared_ptr.hpp>
#include <iostream>

class A {
private:
    int m_data;
public:
    A(int value=0) { m_data = value; }
    ~A() { std::cout << "destroying A(" << m_data << ")" << std::endl; }
    operator int() const { return m_data; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    QList<A *> list;
    list.append(new A(6));
    std::cout << int(*(list.at(0))) << std::endl;
    return 0;
}

Output:

6

Not good.


Need Your Help

MVC 3 Compare Attribute Not Working

jquery asp.net-mvc validation

I am working on an MVC app, which has a registration form where I want to use the Compare, Required and Regex attributes for email validation. The user has to enter their email address, and then co...

Setting proxy in Django

python django proxy

I am trying to send email is using django.core.mail.send_mail(). However I am getting the following error when I try submit the form.