2

I wrote a printf function using std::initializer_list:

template<typename T, typename... Ts>
auto printf(T t, Ts... args) {
    std::cout << t << std::endl;
    return std::initializer_list<T>{([&] {
        std::cout << args << std::endl;
    }(), t)...};
}

int main() {
    printf(111, 123, "alpha", 1.2);
    return 0;
}

The compiler gives a note on instantiation of function template specialization:

warning: returning address of local temporary object [-Wreturn-stack-address]
    return std::initializer_list<T>{([&] {
                                   ^~~~~~~
note: in instantiation of function template specialization 'printf<int, int, const char *, double>' requested here
    printf(111, 123, "alpha", 1.2); 

I aware of returning stack address is a bad practice, however, if I don't do return then I will receive:

warning: expression result unused [-Wunused-value]

How could I change my code to avoid these three type of compiler warnings?

EylM
  • 5,967
  • 2
  • 16
  • 28
Changkun
  • 1,502
  • 1
  • 14
  • 29

2 Answers2

2

Cast initializer_list to void to show the compiler you do not use it intentionally

RiaD
  • 46,822
  • 11
  • 79
  • 123
1

How could I change my code to avoid these three type of compiler warnings?

Don't return the object and use the good old (void)-trick (see e.g. this thread for more info on that):

(void) std::initializer_list<T>{ /* ... */ };

By the way, pretty awesome printf implementation :)

lubgr
  • 37,368
  • 3
  • 66
  • 117