我有一个返回模板类型的默认构造值的函数:
template<typename T>
T do_stuff()
{
return T();
}
我是这样使用的:
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;
}
使用后我有: str
是一个空字符串, a
eqauls 0 和 p
是一个空指针。
我可以理解为什么 std::string
变量会变成空字符串(它具有构造空字符串的默认构造函数)。
但是为什么一个 int
变量变成了 0 而一个指针变成了一个空指针。
它是默认模板行为吗?
我在 Linux Centos 下使用 gcc 4.6.6。
最佳答案
来自 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.
发生的事情是上面列表中的最后一点。
关于c++ - 返回默认构造值的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21302736/