c++ - 返回默认构造值的模板函数

标签 c++ templates default-value

我有一个返回模板类型的默认构造值的函数:

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/

相关文章:

c++ - LNK2019未解析的外部符号。创建二叉树

c++ - lambdas 和 std::function 的包装器

python - 返回默认值

scala - 如何判断 Map 是否有默认值?

c++ - 如何递归删除Qt3DWindow根实体中的所有节点?

python - Tensorflow C++ 推理结果与 Keras 推理略有不同

ruby-on-rails - Rails 条件布局 : Why does ":for" work as an option for the layout method?

python - 如何在 Django 模板中使用模板?

c++ - 几个模板问题(已经解决了...只是想知道为什么)

c++ - Cin 显示默认值