So in writing a C++ template class, I have defined a method that returns an object of the templated type, as such:
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;
}
This gives the following warning:
prog.cpp: In member function ‘T Foo<T>::GetFoo() [with T = int]’:
prog.cpp:15: warning: ‘value’ is used uninitialized in this function
I understand why this is happening - I am returning an uninitialized int
as part of GetFoo
. The thing is, if I were to use Foo<SomeClass>
, the line T value;
would initialize value
using the default constructor of SomeClass
.
I have managed to suppress this warning by doing the following:
T GetFoo()
{
T value = T();
//Do some stuff that might or might not set the value of 'value'
return value;
}
This seems to work for primitive types (such as int
and float
) and classes, at least so long as that class has a default constructor and copy constructor. My question is - is this the accepted way of solving this problem? Are there any side effects of this I should know about?
Sounds OK, if the class has no copy constructor, you will not be able to return it anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With