Re: two types of heap allocated objects--any benefit?
newbie wrote:
Let's see two different usage of an STL container. I see (2) more
often when reading code over (1), dose that give any benefit or it's
purely a coding preference?
Also, please see the (3), I see (3) often in ppl' code, does that give
any benefit over (2)
Thanks for answering in advance:)
[...]
// (1) The first Example definition:
class Example {
public:
Example() {};
~Example() {};
Enque(MyData a) { storage.push_back(a); }
private:
deque<MyData> storage;
}
This is more or less that standard way of doing things in C++.
// (2) We can define Example alternatively, like the following
class Example {
public:
Example() { storage = new deque<MyData>; }
~Example() { delete storage; };
Enque(int a) { storage->push_back(a); }
private:
deque<MyData> *storage;
}
And I've never seen this. What's the point? (In my experience,
pointers to standard containers are very, very rare. The only
occur when several objects share the same container.)
(3) The third approach doing similar thing.
class MyData;
class Example;
int main() {
Example example;
for(int i = 0 ; i < HUGE_NUM; i++) {
MyData* a = new MyData(i);
example.Enque(a);
}
}
class MyData {
public:
MyData(int i) {data = i; }
int data;
}
class Example {
public:
Example() { storage = new deque<MyData>; }
~Example() {
while (!storage->empty()) {
MyData* a = storage->pop_front();
delete a;
}
delete storage;
}
Enque(MyData *a) { storage->push_back(a); }
private:
deque<MyData*> *storage;
}
Again, fairly rare. As I mentioned above, it would be very rare
to have a pointer to a container. It's not particularly rare,
however, for containers to contain pointers, and while not
usually the case, it sometimes happens that they own the
pointers as well, and are responsible for deleting them. (This
most often happens when the contained object has identity, and
is not copiable.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34