Question:
c++ qt4 memory management : 2 questions?
Ashley Durban SA
2010-10-04 04:22:29 UTC
Refer to the following code fragment for the questions below:
1. void foo() {
2. Thing* tp1 = new Thing(1);
3. Thing* tp2 = new Thing(2);
4. Thing* tp3 = new Thing(3);
5. }
2.1
This function represents bad C++ practice because it creates memory leaks. Explain.

-

Say we make the Thing class inherit from QObject as follows:
class Thing : public QObject {
public:
Thing(int n, QObject* p = NULL)
: num(n) {
setParent(p);
}
// other member functions of Thing
private:
int num;
// other data members of Thing
};
Rewrite the foo() function so that it uses the child management facility inherited from QObject to prevent any memory leaks. (Note: The function should still declare at least three pointers to Things, and allocate heap memory to them.)
Three answers:
Cubbi
2010-10-04 06:18:11 UTC
1. Yes, C pointers represent bad C++ practice because they cannot be used to manage ownership and require manual deallocation to manage lifetime (omitted in your example, and that omission causes a memory leak).



Depending on the ownership model intended for those pointers, the correct modern C++ syntax would be:

   std::unique_ptr tp1(new Thing(1)); // if ownership is never shared

or

   std::shared_ptr tp1 = std::make_shared(1); // if ownership is shared

In the old (1998) C++, this would have been

   std::auto_ptr tp1(new Thing(1)); // has caveats



2. QT, like many old C++ frameworks, provides its own memory management that duplicates C++. Instead of the C++ pointers, you are encouraged to use the QT pointers, such as QSharedPointer or QScopedPointer or even QSharedDataPointer.



Your assignment is probably asking you to create a QObject, assign ownership of Thing to that object, and use C pointers, though.
?
2016-11-16 18:07:43 UTC
I do C++, there i might return a pointer to the article declared interior the calling approach and surpassed into the (so going out of scope won't ensue because of the fact the dispensed reminiscence could be related to the pointer which could be available interior of to the tactic to which you back the pointer). In C++ the equivalent of 'alloc' is 'new' and in C++ you need to then merely 'delete' the pointer, after use.
anonymous
2010-10-04 05:22:27 UTC
Stop copying and pasting your test questions and actually ask a damn question.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...