Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template function that returns default constructed value

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.

like image 252
hank Avatar asked Jan 23 '14 08:01

hank


People also ask

Can constructor be a template function?

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.

What is a templated function?

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.

Can we use template in main function?

main cannot be a function template; it must be a function.


1 Answers

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.

like image 198
Some programmer dude Avatar answered Nov 15 '22 19:11

Some programmer dude