I have a function that returns default constructed value of template type:
template<typename T>
T do_stuff()
{
return T();
}
I use it like this:
int main(int argc, char** argv)
{
std::string str("hello");
int a = 10;
int *p = &a;
str = do_stuff<std::string>();
a = do_stuff<int>();
p = do_stuff<int*>();
return 0;
}
After I use it I have: str
is an empty string, a
eqauls 0 and p
is a null pointer.
I can understand why std::string
variable becomes an empty string (it has default constructor that constructs an empty string).
But why an int
variable becomes 0 and a pointer becomes a null pointer.
Is it default template behaviour?
I use gcc 4.6.6 under Linux Centos.
Destructors and copy constructors cannot be templates. If a template constructor is declared which could be instantiated with the type signature of a copy constructor, the implicitly-declared copy constructor is used instead.
Function templates are similar to class templates but define a family of functions. With function templates, you can specify a set of functions that are based on the same code but act on different types or classes.
main cannot be a function template; it must be a function.
From this reference on value initialization:
If T is a class type with at least one user-provided constructor of any kind, the default constructor is called.
If T is an non-union class type without any user-provided constructors, then the object is zero-initialized and then the implicitly-declared default constructor is called (unless it's trivial)
If T is an array type, each element of the array is value-initialized
Otherwise, the object is zero-initialized.
What is happening is that the last point in the above list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With