所以在编写C++模板类时,我已经定义了一个返回模板化类型对象的方法,如下所示:
template <typename T>
class Foo
{
public:
T GetFoo()
{
T value;
//Do some stuff that might or might not set the value of 'value'
return value;
}
};
int main() {
Foo<int> foo;
foo.GetFoo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这给出了以下警告:
prog.cpp: In member function ‘T Foo<T>::GetFoo() [with T = int]’:
prog.cpp:15: warning: ‘value’ is used uninitialized in this function
Run Code Online (Sandbox Code Playgroud)
我明白为什么会发生这种情况 - 我将返回一个未初始化int的部分GetFoo.问题是,如果我要使用Foo<SomeClass>,该行将使用默认构造函数T value;初始化.valueSomeClass
我设法通过执行以下操作来抑制此警告:
T GetFoo()
{
T value = T();
//Do some stuff that might or might not set the value of 'value'
return value;
}
Run Code Online (Sandbox Code Playgroud)
这似乎适用于原始类型(如int和float)和类,至少只要该类具有默认构造函数和复制构造函数.我的问题是 - 这是解决这个问题的公认方式吗?我应该知道这有什么副作用吗?