Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to distinguish two zero-arg constructors

I have a class like this:

struct event_counts {     uint64_t counts[MAX_COUNTERS];      event_counts() : counts{} {}      // more stuff  };  

Usually I want to default (zero) initialize the counts array as shown.

At selected locations identified by profiling, however, I'd like to suppress the array initialization, because I know the array is about to be overwritten, but the compiler isn't smart enough to figure it out.

What's an idiomatic and efficient way to create such a "secondary" zero-arg constructor?

Currently, I'm using a tag class uninit_tag which is passed as a dummy argument, like so:

struct uninit_tag{};  struct event_counts {     uint64_t counts[MAX_COUNTERS];      event_counts() : counts{} {}      event_counts(uninit_tag) {}      // more stuff  }; 

Then I call the no-init constructor like event_counts c(uninit_tag{}); when I want to suppress construction.

I'm open to solutions that don't involve the creation of a dummy class, or are more efficient in some way, etc.

like image 880
BeeOnRope Avatar asked Nov 16 '19 00:11

BeeOnRope


People also ask

How is a no-arg constructor defined?

Example 2: Java private no-arg constructor Here, the constructor does not accept any parameters. Hence, it is known as a no-arg constructor. Notice that we have declared the constructor as private. Once a constructor is declared private , it cannot be accessed from outside the class.

Is the default constructor and the no args constructor the same thing?

Answer to your question is No. Java won't provide a default constructor if you write any kind of constructor in class. One difference between them is that the body of default constructor will always be empty whereas we can insert our own code in no-arg constructor.

What is the purpose of a no argument constructor?

In Java, a no-argument constructor is the default constructor and if you don't define explicitly in your program. Then Java Compiler will create a default constructor with no arguments. The purpose is to call the superclass constructor.

Can two constructors have the same parameters?

The technique of having two (or more) constructors in a class is known as constructor overloading. A class can have multiple constructors that differ in the number and/or type of their parameters. It's not, however, possible to have two constructors with the exact same parameters.


1 Answers

The solution you already have is correct, and is exactly what I'd want to see if I were reviewing your code. It is as efficient as possible, clear and concise.

like image 111
John Zwinck Avatar answered Sep 23 '22 08:09

John Zwinck