考虑中

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,例如当Tint。另一方面,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>类模板,该模板基本上执行相同的操作,具有更大的灵活性和一致性,并且具有适用于错误编译器的变通办法。

在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/

10-11 15:24
查看更多