Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

c++ - 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.

question from:https://stackoverflow.com/questions/58886223/idiomatic-way-to-distinguish-two-zero-arg-constructors

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...