QList and shared_ptr

What do you think? Is this correct or is there a memory leak?

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)
+5
source share
4 answers

Seems right. Boost shared_ptr - reference count pointer. The reference counter may return memory if there are no round links between objects. In your case, objects of class A do not refer to any other objects. This way you can use shared_ptr without worries. In addition, property semantics allow the use of shared_ptrs in STL (and Qt) containers.

+1
source

It is hard to suggest anything without knowing why there is a list shared_ptrof A.

. , .

, :

1. ctor, :

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

2. int _tmain(int argc, _TCHAR* argv[]) ;

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

:

int main()
+1

.

, , , shared_ptr QList, "Qt" , , shared_ptr.

+1

-, .

:

#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;
}

:

6

.

+1

All Articles