草庐IT

c++ - 模板函数 : default construction without copy-constructing in C++

coder 2024-02-03 原文

考虑

struct C { 
   C()            { printf("C::C()\n"          ); }
   C(int)         { printf("C::C(int)\n"       ); }
   C( const C& )  { printf("copy-constructed\n"); }
};

还有一个模板函数

template< typename T > void foo(){
    // default-construct a temporary variable of type T
    // this is what the question is about.
    T t1;       // will be uninitialized for e.g. int, float, ...
    T t2 = T(); // will call default constructor, then copy constructor... :(
    T t3();     // deception: this is a local function declaration :(
}

int main(){
    foo<int>();
    foo<C  >();
}

查看t1,当T为例如整数。另一方面,t2复制构造自一个默认构造的临时变量。

问题:在 C++ 中是否可以默认构造泛型变量,而不是使用 template-fu?

最佳答案

这里有一个你可以使用的技巧,使用本地类:

template <typename T> void foo() {
    struct THolder {
        T obj;
        THolder() : obj() { } // value-initialize obj
    };

    THolder t1; // t1.obj is value-initialized
}

我想我是从另一个 Stack Overflow 问题的答案中了解到这个技巧的,但我目前找不到那个问题。

或者,您可以使用 boost::value_initialized<T>类模板,它基本上做同样的事情,具有更大的灵 active 和一致性,并为有问题的编译器提供了变通办法。

在 C++0x 中,这要容易得多:您可以使用一个空的初始化列表:

T obj{}; // obj is value-initialized

(据我所知,只有 gcc 4.5+ 支持 C++0x 初始化列表。Clang 和 Visual C++ 尚不支持它们。)

关于c++ - 模板函数 : default construction without copy-constructing in C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5303019/

有关c++ - 模板函数 : default construction without copy-constructing in C++的更多相关文章

随机推荐