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
496 views
in Technique[技术] by (71.8m points)

c++ - How to initialize to zero/NULL in a template

While writing a template, I want to initialize my variable to a value that serves as zero or null the the data type. If I set it to 0x00 is it going to serve as zero/NULL for any type ?

for example

This is template declaration

template <class T>
...
T A=0x00;

Now if I define an instance of type T => std::string the above statement serves as NULL ?

What about "int" and "unsigned int". For both of the it serves as "0" ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use Value Initialization:

T A = T(); // before C++11

T A{}; // C++11 and later

The effects of value initialization are:

1) if T is a class type with at least one user-provided constructor of any kind, the default constructor is called;
(until C++11)

1) if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;
(since C++11)

2) if T is an non-union class type without any user-provided constructors, every non-static data member and base-class component of T is value-initialized;
(until C++11)

2) if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;
(since C++11)

3) if T is an array type, each element of the array is value-initialized;

4) otherwise, the object is zero-initialized.


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

...