Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am reviewing an approach I see commonly used in storing objects (e.g. a socket client object). Namely, usage of a static container to hold the objects. Said objects are created by some helper function as follows:

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

i.e. 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?

share|improve this question
    
In your second code block, did you mean if (!create_client(...))? – Dan Pichelman Jun 18 '14 at 16:32
    
@DanPichelman - if not created correctly print error. Its not important to question. – user619818 Jun 18 '14 at 16:44
    
Dan means that you define the function as client_create and later use it as create_client. – SJuan76 Jun 18 '14 at 17:00
    
Well spotted! I have edited. – user619818 Jun 18 '14 at 17:01
up vote 3 down vote accepted

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.

share|improve this answer

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

No, and no, unless you count "Terrible" as an idiom name. There is no such thing as idiomatic mutable global state. Idioms exist to avoid such crap.

share|improve this answer
    
"Idioms exist to avoid such crap." Unless it's the singleton idiom (cough). Now where's the mouthwash? – Thomas Eding Jun 18 '14 at 22:05
4  
Singleton is not an idiom. It is an idiot filter. – DeadMG Jun 18 '14 at 22:11

This thing is called a multiton, so, yes, it is an idiom. It's not a good practice, though.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.