C++ idiom to avoid memory leaks? - c++

In the following code, there is a memory leak if Info::addPart1() is called multiple times by accident:
typedef struct
{
}part1;
typedef struct
{
}part2;
class Info
{
private:
part1* _ptr1;
part2* _ptr2;
public:
Info()
{
_ptr1 = _ptr2 = NULL;
}
~Info()
{
delete _ptr1;
delete _ptr2;
}
addPart1()
{
_ptr1 = new part1;
}
addPart2()
{
_ptr2 = new part2;
}
};
Info _wrapper;
_wrapper.addPart1();
_wrapper.addPart2();
Is there a C++ idiom to handle this problem ?
I could rewrite addPart1 and addPart2 like this to defend the MLK
addPart1()
{
if(_ptr1 != NULL) delete _ptr1;
_ptr1 = new part1;
}
Is that a good solution?

Use a smart pointer such as boost:shared_ptr , boost:scoped_ptr is recommended to manage the raw pointer. auto_ptr is tricky to work with, you need pay attention to that.

You should read about the smart pointer idiom and about RAII.
I suggest taking a look into the new technical report (TR1).
Take a good look here and here.
Also take a look at boost's smart pointers.
I recommend loki-lib's SmartPtr or StrongPtr classes.

Bear with me here...
In the distant past, programmers used constructs like "jump" and "goto" for flow control. Eventually common patterns emerged and constructs like for, do/while, function call and try/catch emerged, and the spaghetti was tamed. Those named constructs give a lot more information about intent than a generic goto, where you have to examine the rest of the code for context to understand what it's doing. In the unlikely event you see a goto in modern code by a competent coder, you know something pretty unusual is going on.
In my opinion, "delete" is the "goto" of memory management. There are enough smart pointer and container classes available to the modern developer that there's very little reason for most code to contain a single explicit delete (other than in the smart pointer implementations of course). When you see a plain "delete" you get no information about intent; when you see a scoped_ptr/auto_ptr/shared_ptr/ptr_container you get a lot more.
ie the idiom should be to aspire to write delete-free code by using appropriate smart pointer types (as recommended by just about every other answer here).
Update 2013-01-27: I note Herb Sutter's excellent talk on C++11 includes some similar sentiments re delete free code.

Checking for nonzero pointer before delete is redundant. delete 0 is guaranteed to be a no-op.
A common way to handle this is
delete _ptr1;
_ptr1 = 0;
_ptr1 = new part1;
Zeroing the pointer ensures there won't be any dangling pointers for example in the case part1 construction throws an exception.

Your suggested fix will work (though of course you're still at risk for a memory leak if addPart2() is called twice). A much safer approach is to use scoped_ptr from the Boost library collection (www.boost.org), which is a container that acts like a pointer, but guarantees that its target is deleted when the container is destroyed. Your revised class would then look like
class Info
{
private:
boost::scoped_ptr<part1> _ptr1;
boost::scoped_ptr<part2> _ptr2;
public:
Info() {} // scoped_ptrs default to null
// You no longer need an explicit destructor- the implicit destructor
// works because the scoped_ptr destructor handles deletion
addPart1()
{
_ptr1.reset(new part1);
}
addPart2()
{
_ptr2.reset(new part2);
}
};
As a general principle, it's a good idea to avoid writing code that requires you to explicitly delete pointers. Instead, try to use containers that do it automatically at the appropriate time. Boost is a good resource for this kind of thing.
All this assumes you have a reason ptr1_ and ptr2_ need to be pointers. If not, it's much better to make them ordinary objects; then you get memory management for free.

Use construction is initialization instead.
class Info
{
private:
part1* _ptr1;
part2* _ptr2;
public:
Info() : _ptr1(new part1), _ptr2(new part2)
{
}
~Info()
{
delete _ptr1;
delete _ptr2;
}
};
But in this case you might as well create the parts on the stack, so no new and delete is required.
class Info
{
private:
part1 _part1;
part2 _part2;
public:
Info()
{
}
~Info()
{
}
};
But I guess you want the pointers to be lazy created, then I wouldn't suggest to create public class methods that takes care of the initializations. This should be handled internally in the class, when the class need to allocate them.

If you want it to have a lazy behavior you might consider this:
addPart1()
{
if(_ptr1 == NULL) {
_ptr1 = new part1;
}
}
The way you suggested is also an alternative depending how you want it to behave.
But other people have suggested better ways to do it, but as we really don't know why you made it this way and how the surrounding code works ...

I agree with the group that you should use some kind of smart pointer.
If you do decide to continue with bare pointers, be aware that your class above does not have a copy constructor defined by you. Therefore, the C++ compiler has defined one for you that will just do a simple copy of all the pointers; which will lead to a double delete. You'll need to define your own copy constructor (or at least create a stub private copy constructor if you don't think you need a copy constructor).
Info(const Info &rhs)
{
_ptr1 = new part1[rhs._ptr1];
_ptr2 = new part2[rhs._ptr2];
}
You will have a similar problem with the default assignment operator.
If you choose the correct smart pointer, these problems will go away. :)

Option 1: Use Java :)
Option 2: Use auto_ptr
std::auto_ptr<part1> _ptr1;
std::auto_ptr<part2> _ptr2;
public:
addPart1()
{
_ptr1 = auto_ptr<part1>(new part1);
}
...
// no destructor is needed

You should take a look at RAII

On the far extreme of possible ways to deal with memory leaks is the boehm garbage collector, a conservative mark & sweep collector. Interestingly, this can be used in addition to all the good advice offered in other answers.

Related

Is it mandatory to delete a pointer variable within a structure, before deleting the structure?

I have started to C++ and need some clarifications regarding memory management in C++. I have come across smart pointers, but I wish to understand some basic concepts.
Here's a sample structure
struct A
{
private:
int a;
void* b;
public:
A(int i, void* m) { a=i; b=m; }
};
main()
{
A * a1 = new A(10, 0);
//
//Some Code
if(on some condition) {
delete a1;
a1=nullptr;
}
}
When I delete a1, will m also be deleted automatically or should i explicitly delete m before deleting a1 as given below?
delete a1->b;
a1->b = nullptr;
delete a1;
a1=nullptr;
When I delete a1, will m also be deleted automatically
No, it won't (your code probably has a memory leak). You need an explicit destructor deleting it.
BTW, using a void*b; pointer field is poor taste. You should prefer some more explicit type (e.g. double*b; or SomeClass* b;) if you know it. This makes your code more readable, and give more opportunities for helpful type checking at compile time.
// inside struct A
~A() { delete b; };
Read about the rule of five.
Notice that struct-s are very similar to class-es in C++.
Avoid memory leaks. Tools like valgrind could be helpful. And using systematically smart pointers and standard containers should help to avoid them. If your field b was declared std::shared_ptr<std::string> b; the default destructor would have freed it appropriately. And perhaps you want it to be some std::vector<std::string> (again, the default destructor is releasing memory appropriately).
A good coding hint is to avoid, when possible, declaring raw pointers (prefer smart pointers and containers). When you have to declare one, you need to code its delete appropriately.
Welcome to C++, a very powerful language that requires you to take responsibility of the details to achieve the flexibility that allows such power. If you like, you can make it very complex, however for most constructs their is an easy way as well.
First of all, you ain't required to release memory, if your program exits, it will clean it. However, as you don't call delete, the Dtor will not be called which might cause specific code to not be executed.
So in general, it's good practice to clean up the allocated memory.
If you don't need the heap, don't use it
new A(10, 0) will allocate memory on the heap. If you don't want that, this can as well be created on the stack. Which causes auto cleanup: A a{10, nullptr};
Use RAII
As soon as you decide, you need heap allocated memory, you should default to std::unique_ptr. Which changes the code to: auto a = std::make_unique<A>(10, nullptr); With this, ownership is within the unique_ptr, which can be moved around (std::move). If you don't want to transfer ownership, you can dereference it or call the method get.
Applying these 2 practices, including for members, will prevent a lot of memory leaks and will reduce the time you need to think about it.
Don't use void*
void* is evil, don't use it unless you have to (and you only have to when interfacing with C). There are many ways of avoiding it. The best one is introducing an interface.
class I {
public:
virtual ~I() = default;
};
class M : public I
{
// ...
};
class A
{
// ...
std::unique_ptr<I> m;
// ...
};
Need something special?
Some times, you need something special in the Dtor, only in that case you should implement the Dtor explicitly. Given your question, I'm gonna assume you are a beginner and as such don't need to know about more details for now.

How to ensure (like a try-finally) destruction of a HEAP-ALLOCATED object

I'm looking for a way to ensure that an object that is executed on the heap is ALWAYS deallocated when I'm done with it.
I know that if it's allocated on the stack, I can use RAII to ensure it will be taken care of - unfortunately, this won't work for me (at least directly) because the object in question is actually created by calling an api function, which then returns a pointer to the object it creates on the heap.
So, conceptually, what I want to do is something like:
TheApi::ApiObject* p_myObj = TheApi::createAnApiObj();
try
{
doStuffWithMyObjThatMayError(p_myObj);
}
finally
{
delete p_myObj;
}
The only thing I can think of to do would be to make some sort of dummy cleanup class, and create an instance of that on the stack:
class MegaMaid
{
private:
TheApi::ApiObject* toFree;
public:
MegaMaid(TheApi::ApiObject* toFree)
{
this->toFree = toFree;
}
~MegaMaid()
{
delete toFree;
}
};
void doStuff()
{
TheApi::ApiObject* p_myObj = TheApi::createAnApiObj();
TheApi::ApiObject* p_myObj;
MegaMaid cleaner(p_myObj);
doStuffWithMyObjThatMayError(p_myObj);
}
Is there a better way to accomplish this? Or is this the accepted solution?
You can still use RAII on pointers returned by functions. You can use smart pointers (which is exactly what the dummy class you are describing is) like this:
std::unique_ptr<TheApi::ApiObject> p_myObj(TheApi::createAnApiObj());
That "dummy class" is known as "smart pointer". You should check out std::auto_ptr or boost::shared_ptr. They provide exactly what you look for.

Simplest way to count instances of an object

I would like to know the exact number of instances of certain objects allocated at certain point of execution. Mostly for hunting possible memory leaks(I mostly use RAII, almost no new, but still I could forget .clear() on vector before adding new elements or something similar). Ofc I could have an
atomic<int> cntMyObject;
that I -- in destructor, ++ increase in constructor, cpy constructor(I hope I covered everything :)).
But that is hardcoding for every class. And it is not simple do disable it in "Release" mode.
So is there any simple elegant way that can be easily disabled to count object instances?
Have a "counted object" class that does the proper reference counting in its constructor(s) and destructor, then derive your objects that you want to track from it. You can then use the curiously recurring template pattern to get distinct counts for any object types you wish to track.
// warning: pseudo code
template <class Obj>
class CountedObj
{
public:
CountedObj() {++total_;}
CountedObj(const CountedObj& obj) {++total_;}
~CountedObj() {--total_;}
static size_t OustandingObjects() {return total_;}
private:
static size_t total_;
};
class MyClass : private CountedObj<MyClass>
{};
you can apply this approach
#ifdef DEBUG
class ObjectCount {
static int count;
protected:
ObjectCount() {
count++;
}
public:
void static showCount() {
cout << count;
}
};
int ObjectCount::count = 0;
class Employee : public ObjectCount {
#else
class Employee {
#endif
public:
Employee(){}
Employee(const Employee & emp) {
}
};
at DEBUG mode, invoking of ObjectCount::showCount() method will return count of object(s) created.
Better off to use memory profiling & leak detection tools like Valgrind or Rational Purify.
If you can't and want to implement your own mechanism then,
You should overload the new and delete operators for your class and then implement the memory diagnostic in them.
Have a look at this C++ FAQ answer to know how to do that and what precautions you should take.
This is a sort of working example of something similar: http://www.almostinfinite.com/memtrack.html (just copy the code at the end of the page and put it in Memtrack.h, and then run TrackListMemoryUsage() or one of the other functions to see diagnostics)
It overrides operator new and does some arcane macro stuff to make it 'stamp' each allocation with information that allow it to count how many instances of an object and how much memory they're usingusing. It's not perfect though, the macros they use break down under certain conditions. If you decide to try this out make sure to include it after any standard headers.
Without knowing your code and your requirements, I see 2 reasonable options:
a) Use boost::shared_ptr. It has the atomic reference counts you suggested built in and takes care of your memory management (so that you'd never actually care to look at the count). Its reference count is available through the use_count() member.
b) If the implications of a), like dealing with pointers and having shared_ptrs everywhere, or possible performance overhead, are not acceptable for you, I'd suggest to simply use available tools for memory leak detection (e.g. Valgrind, see above) that'll report your loose objects at program exit. And there's no need to use intrusive helper classes for (anyway debug-only) tracking object counts, that just mess up your code, IMHO.
We used to have the solution of a base class with internal counter and derive from it, but we changed it all into boost::shared_ptr, it keeps a reference counter and it cleans up memory for you. The boost smart pointer family is quite useful:
boost smart pointers
My approach, which outputs leakage count to Debug Output (via the DebugPrint function implemented in our code base, replace that call with your own...)
#include <typeinfo>
#include <string.h>
class CountedObjImpl
{
public:
CountedObjImpl(const char* className) : mClassName(className) {}
~CountedObjImpl()
{
DebugPrint(_T("**##** Leakage count for %hs: %Iu\n"), mClassName.c_str(), mInstanceCount);
}
size_t& GetCounter()
{
return mInstanceCount;
}
private:
size_t mInstanceCount = 0;
std::string mClassName;
};
template <class Obj>
class CountedObj
{
public:
CountedObj() { GetCounter()++; }
CountedObj(const CountedObj& obj) { GetCounter()++; }
~CountedObj() { GetCounter()--; }
static size_t OustandingObjects() { return GetCounter(); }
private:
size_t& GetCounter()
{
static CountedObjImpl mCountedObjImpl(typeid(Obj).name());
return mCountedObjImpl.GetCounter();
}
};
Example usage:
class PostLoadInfoPostLoadCB : public PostLoadCallback, private CountedObj<PostLoadInfoPostLoadCB>
Adding counters to individual classes was discussed in some of the answers. However, it requires to pick the classes to have counted and modify them in one way or the other. The assumption in the following is, you are adding such counters to find bugs where more objects of certain classes are kept alive than expected.
To shortly recap some things mentioned already: For real memory leaks, certainly there is valgrind:memcheck and the leak sanitizers. However, for other scenarios without real leaks they do not help (uncleared vectors, map entries with keys never accessed, cycles of shared_ptrs, ...).
But, since this was not mentioned: In the valgrind tool suite there is also massif, which can provide you with the information about all pieces of allocated memory and where they were allocated. However, let's assume that valgrind:massif is also not an option for you, and you truly want instance counts.
For the purpose of occasional bug hunting - if you are open for some hackish solution and if the above options don't work - you might consider the following: Nowadays, many objects on the heap are effectively held by smart pointers. This could be the smart pointer classes from the standard library, or the smart pointer classes of the respective helper libraries you use. The trick is then the following (picking the shared_ptr as an example): You can get instance counters for many classes at once by patching the shared_ptr implementation, namely by adding instance counts to the shared_ptr class. Then, for some class Foo, the counter belonging to shared_ptr<Foo> will give you an indication of the number of instances of class Foo.
Certainly, it is not quite as accurate as adding the counters to the respective classes directly (instances referenced only by raw pointers are not counted), but possibly it is accurate enough for your case. And, certainly, this is not about changing the smart pointer classes permanently - only during the bug hunting. At least, the smart pointer implementations are not too complex, so patching them is simple.
This approach is much simpler than the rest of the solutions here.
Make a variable for the count and make it static. Increase that variable by +1 inside the constructor and decrease it by -1 inside the destructor.
Make sure you initialize the variable (it cannot be initialized inside the header because its static).
.h
// Pseudo code warning
class MyObject
{
MyObject();
~MyObject();
static int totalObjects;
}
.cpp
int MyObject::totalObjects = 0;
MyObject::MyObject()
{
++totalObjects;
}
MyObject::~MyObject()
{
--totalObjects;
}
For every new instance you make, the constructor is called and totalObjects automatically grows by 1.

Memory Management with returning char* function

Today, without much thought, I wrote a simple function return to a char* based on a switch statement of given enum values. This, however, made me wonder how I could release that memory. What I did was something like this:
char* func()
{
char* retval = new char[20];
// Switch blah blah - will always return some value other than NULL since default:
return retval;
}
I apologize if this is a naive question, but what is the best way to release the memory seeing as I cannot delete the memory after the return and, obviously, if I delete it before, I won't have a returned value. What I was thinking as a viable solution was something like this
void func(char*& in)
{
// blah blah switch make it do something
}
int main()
{
char* val = new char[20];
func(val);
// Do whatever with func (normally func within a data structure with specific enum set so could run multiple times to change output)
delete [] val;
val = NULL;
return 0;
}
Would anyone have anymore insight on this and/or explanation on which to use?
Regards,
Dennis M.
You could write such functions in pair, like
Xyz* CreateXyz();
void DestroyXyz(Xyz *xyz);
Abc* NewAbc();
void DeleteAbc(Abc *abc);
Or you simply can transfer the responsibilty of deleting Xyz/Abc to the clients, i.e ones who call the function must also do delete on the returned object after using it.
Whatever you choose, make it clear in your documentation how the created object should be destroyed.
I would prefer pair-functions, especially if there is lot of things to consider before deleting!
By the way, you should prefer using std::string, instead of char*. Make use of STL as much as you can. They can solve most of your problems! The above advice is for situations where STL doesn't fit! In general, prefer STL!
Have you considered using an STL type or other class instead of returning a raw pointer? For instance, if your char * is a string, use std::string instead and avoid any risk of leaks:
std::string func()
{
std::string retval("");
// Switch blah blah - will always return some value other than NULL since default:
return retval;
}
If you plan to return raw pointers from a function, you must make really clear on the documentation whose is the responsibility of deleting the pointer, i.e. who owns it. In this case, you should state explicitly that the pointer ownership is transferred to the caller, who is responsible to delete it.
Although many people are OK with just specifying the ownership in the documentation, often it's better to enforce this policy in the code. In particular, smart pointers are often used for this: the current C++ standard provides the std::auto_ptr, a smart pointer which transfers ownership on copy, i.e. when you return it to the caller, you're transferring the ownership to the target std::auto_ptr. Notice that std::auto_ptr automagically deletes the pointed memory on its destruction if it still owns it. The upcoming C++ standard provides std::unique_ptr that works in a similar fashion, but using move semantic.
Unfortunately, std::auto_ptr isn't thought for arrays (which need delete [] instead of delete), so you cannot use for your your purpose. I think that the decision of not including an auto_ptr for arrays was made deliberately, because the STL already provides all the containers you may need if you need to return a collection of items which handle by their own memory management and copy.
In particular, for strings you should simply use std::string and forget completely about this kind of memory management and pointer ownership problems.
In this case whoever calls the func() should release the memory when its not needed. But the correct deletion happens like this:
delete val;
val = NULL;

C++ best practice: Returning reference vs. object

I'm trying to learn C++, and trying to understand returning objects. I seem to see 2 ways of doing this, and need to understand what is the best practice.
Option 1:
QList<Weight *> ret;
Weight *weight = new Weight(cname, "Weight");
ret.append(weight);
ret.append(c);
return &ret;
Option 2:
QList<Weight *> *ret = new QList();
Weight *weight = new Weight(cname, "Weight");
ret->append(weight);
ret->append(c);
return ret;
(of course, I may not understand this yet either).
Which way is considered best-practice, and should be followed?
Option 1 is defective. When you declare an object
QList<Weight *> ret;
it only lives in the local scope. It is destroyed when the function exits. However, you can make this work with
return ret; // no "&"
Now, although ret is destroyed, a copy is made first and passed back to the caller.
This is the generally preferred methodology. In fact, the copy-and-destroy operation (which accomplishes nothing, really) is usually elided, or optimized out and you get a fast, elegant program.
Option 2 works, but then you have a pointer to the heap. One way of looking at C++ is that the purpose of the language is to avoid manual memory management such as that. Sometimes you do want to manage objects on the heap, but option 1 still allows that:
QList<Weight *> *myList = new QList<Weight *>( getWeights() );
where getWeights is your example function. (In this case, you may have to define a copy constructor QList::QList( QList const & ), but like the previous example, it will probably not get called.)
Likewise, you probably should avoid having a list of pointers. The list should store the objects directly. Try using std::list… practice with the language features is more important than practice implementing data structures.
Use the option #1 with a slight change; instead of returning a reference to the locally created object, return its copy.
i.e. return ret;
Most C++ compilers perform Return value optimization (RVO) to optimize away the temporary object created to hold a function's return value.
In general, you should never return a reference or a pointer. Instead, return a copy of the object or return a smart pointer class which owns the object. In general, use static storage allocation unless the size varies at runtime or the lifetime of the object requires that it be allocated using dynamic storage allocation.
As has been pointed out, your example of returning by reference returns a reference to an object that no longer exists (since it has gone out of scope) and hence are invoking undefined behavior. This is the reason you should never return a reference. You should never return a raw pointer, because ownership is unclear.
It should also be noted that returning by value is incredibly cheap due to return-value optimization (RVO), and will soon be even cheaper due to the introduction of rvalue references.
passing & returning references invites responsibilty.! u need to take care that when you modify some values there are no side effects. same in the case of pointers. I reccomend you to retun objects. (BUT IT VERY-MUCH DEPENDS ON WHAT EXACTLY YOU WANT TO DO)
In ur Option 1, you return the address and Thats VERY bad as this could lead to undefined behaviour. (ret will be deallocated, but y'll access ret's address in the called function)
so use return ret;
It's generally bad practice to allocate memory that has to be freed elsewhere. That's one of the reasons we have C++ rather than just C. (But savvy programmers were writing object-oriented code in C long before the Age of Stroustrup.) Well-constructed objects have quick copy and assignment operators (sometimes using reference-counting), and they automatically free up the memory that they "own" when they are freed and their DTOR automatically is called. So you can toss them around cheerfully, rather than using pointers to them.
Therefore, depending on what you want to do, the best practice is very likely "none of the above." Whenever you are tempted to use "new" anywhere other than in a CTOR, think about it. Probably you don't want to use "new" at all. If you do, the resulting pointer should probably be wrapped in some kind of smart pointer. You can go for weeks and months without ever calling "new", because the "new" and "delete" are taken care of in standard classes or class templates like std::list and std::vector.
One exception is when you are using an old fashion library like OpenCV that sometimes requires that you create a new object, and hand off a pointer to it to the system, which takes ownership.
If QList and Weight are properly written to clean up after themselves in their DTORS, what you want is,
QList<Weight> ret();
Weight weight(cname, "Weight");
ret.append(weight);
ret.append(c);
return ret;
As already mentioned, it's better to avoid allocating memory which must be deallocated elsewhere. This is what I prefer doing (...these days):
void someFunc(QList<Weight *>& list){
// ... other code
Weight *weight = new Weight(cname, "Weight");
list.append(weight);
list.append(c);
}
// ... later ...
QList<Weight *> list;
someFunc(list)
Even better -- avoid new completely and using std::vector:
void someFunc(std::vector<Weight>& list){
// ... other code
Weight weight(cname, "Weight");
list.push_back(weight);
list.push_back(c);
}
// ... later ...
std::vector<Weight> list;
someFunc(list);
You can always use a bool or enum if you want to return a status flag.
Based on experience, do not use plain pointers because you can easily forget to add proper destruction mechanisms.
If you want to avoid copying, you can go for implementing the Weight class with copy constructor and copy operator disabled:
class Weight {
protected:
std::string name;
std::string desc;
public:
Weight (std::string n, std::string d)
: name(n), desc(d) {
std::cout << "W c-tor\n";
}
~Weight (void) {
std::cout << "W d-tor\n";
}
// disable them to prevent copying
// and generate error when compiling
Weight(const Weight&);
void operator=(const Weight&);
};
Then, for the class implementing the container, use shared_ptr or unique_ptr to implement the data member:
template <typename T>
class QList {
protected:
std::vector<std::shared_ptr<T>> v;
public:
QList (void) {
std::cout << "Q c-tor\n";
}
~QList (void) {
std::cout << "Q d-tor\n";
}
// disable them to prevent copying
QList(const QList&);
void operator=(const QList&);
void append(T& t) {
v.push_back(std::shared_ptr<T>(&t));
}
};
Your function for adding an element would make use or Return Value Optimization and would not call the copy constructor (which is not defined):
QList<Weight> create (void) {
QList<Weight> ret;
Weight& weight = *(new Weight("cname", "Weight"));
ret.append(weight);
return ret;
}
On adding an element, the let the container take the ownership of the object, so do not deallocate it:
QList<Weight> ql = create();
ql.append(*(new Weight("aname", "Height")));
// this generates segmentation fault because
// the object would be deallocated twice
Weight w("aname", "Height");
ql.append(w);
Or, better, force the user to pass your QList implementation only smart pointers:
void append(std::shared_ptr<T> t) {
v.push_back(t);
}
And outside class QList you'll use it like:
Weight * pw = new Weight("aname", "Height");
ql.append(std::shared_ptr<Weight>(pw));
Using shared_ptr you could also 'take' objects from collection, make copies, remove from collection but use locally - behind the scenes it would be only the same only object.
All of these are valid answers, avoid Pointers, use copy constructors, etc. Unless you need to create a program that needs good performance, in my experience most of the performance related problems are with the copy constructors, and the overhead caused by them. (And smart pointers are not any better on this field, I'd to remove all my boost code and do the manual delete because it was taking too much milliseconds to do its job).
If you're creating a "simple" program (although "simple" means you should go with java or C#) then use copy constructors, avoid pointers and use smart pointers to deallocate the used memory, if you're creating a complex programs or you need a good performance, use pointers all over the place, and avoid copy constructors (if possible), just create your set of rules to delete pointers and use valgrind to detect memory leaks,
Maybe I will get some negative points, but I think you'll need to get the full picture to take your design choices.
I think that saying "if you're returning pointers your design is wrong" is little misleading. The output parameters tends to be confusing because it's not a natural choice for "returning" results.
I know this question is old, but I don't see any other argument pointing out the performance overhead of that design choices.