简体   繁体   中英

When using Templates in C++, what does the “T()” function do?

What does the T() do? I have been looking for awhile and can't get a definitive answer.

    Vector<T>::Vector(const Vector<T> & v)
{
    my_size = v.my_size;
    my_capacity = v.my_capacity;
    buffer = new T[my_capacity];
    for (int i = 0; i < my_size; i++)
        buffer[i] = v.buffer[i];
    for (int i = my_size; i< my_capacity; i++)
        buffer[i] = T();
}

T() creates an object of type T which is value-initialized. For arithmetic and pointer types this means they are zero-initialized, while for class types it means the default constructor is called. You can see more details here: http://en.cppreference.com/w/cpp/language/value_initialization

You can also use this syntax outside templates. For example

typedef int T;
T x = T(); // sets x to 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM