Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In code I am reviewing a common approach I see to storing objects (eg a socket c

ID: 658562 • Letter: I

Question

In code I am reviewing a common approach I see to storing objects (eg a socket client object), is use a static container to hold the objects. The objects are created by some helper function, eg like this:

create_client(params) {
...
client* cl = new client(...);
return cl;
}
The thing that confused me at first was function called like this:

if (!create_client (...))
   //generate error message
ie a copy of the pointer just seems to be thrown away.

But on investigation I see this in the client constructor:

client::client(...) {
    ...
    coll[id] = this;
}
Where coll is a map of id to a pointer to the object. But anyway, just a collection. coll is static (not sure if that is relevant).

Is there a name for this idiom? Is it good practice?

Explanation / Answer

Not so familiar with C++, but I do not like the assignment into the static structure from the constructor, because:

1) Introduces a dependency: now the contained class needs to know about the containing instance. You cannot reuse the class without either rewritting or using the same structure.

2) It causes a reference leak from the constructor, since the reference to the class is available to other threads before the constructor has finished executing.

At the very least, I would have moved the instance assignment from the constructor to the create_client function.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote