So, having written a C ++ template class, I defined a method that returns an object of a template type, as such:
template <typename T> class Foo { public: T GetFoo() { T value;
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 return an uninitialized int as part of GetFoo . The fact is that if I used Foo<SomeClass> , the string is T value; would initialize value using the default SomeClass .
I was able 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 is similar to primitive types (like int and float ) and classes, at least as long as this class has a default constructor and a copy constructor. Is my question a common way to solve this problem? Are there any side effects of this that I should know about?
c ++ templates
James
source share