let’s assume that I have some codes like this. What should I write there in order to have a constructor that initializes a Foo typed object. Thanks. this is the example I am trying to understand http://flylib.com/books/en/2.674.1.140/1/ sorry for the delay.
class Foo
{
private:
set<int*> numbers;
public:
//constuctor
Foo(set<int*>& numb = "what to write here?"): numbers("something") {};
};
Having a set of pointers usually isn’t what you want. sets are a collection of unique items, but a set of pointers means each pointer will be unique, not the values they point to.
Steve Jessop points out some more reasons not to want a container of pointers. For one, it’s not clear who owns the pointers at what point, and so it’s not clear how to handle errors. Part of sorting that out could mean imposing stricter requirements on the pointers, for example requiring them to be new allocated so that the object taking ownership knows how to release them. Such requirements will probably only be enforced by manual inspection of the code and documentation, and so will be error prone. That could be improved on by using smart pointers instead of raw pointers.
But if for some reason you really do want this with raw pointers, then:
Or use overloading instead:
Or if you really want to construct numbers as a non-empty set by default you can do the following (dangerous, leak prone) things:
Or using C++11:
or
Fixing the leaks above using smart pointers yields something like:
Using brace initialization with smart pointers like the following still has the possibility for leaks:
So instead you should use a helper function to produce the default value: