Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Return Type with Default Value

Tags:

c++

templates

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?

like image 606
James Avatar asked Dec 12 '22 15:12

James


1 Answers

Sounds OK, if the class has no copy constructor, you will not be able to return it anyway.

like image 126
ysdx Avatar answered Dec 30 '22 02:12

ysdx