Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...