Andrew Tomazos
Andrew Tomazos

Reputation: 68738

C++11 `nullptr_t` returning function being elided?

The following C++11 program doesn't output anything under gcc 4.7.2:

#include <iostream>
using namespace std;

decltype(nullptr) g()
{
    cout << "foo" << endl;
    return nullptr;
}

int* f()
{
    return g();
}

int main(int argc, char** argv)
{
    auto x = f();
}

Is this correct behaviour, or is it a compiler bug?

Update:

Thanks guys. FYI here is my workaround:

 struct NullPointer
 {
     template<class T> operator T*()
     {
          volatile decltype(nullptr) np = nullptr;
          return np;
     }
     operator bool()
     {
          volatile bool b = false;
          return b;
     }
 };

 NullPointer g() { return {}; }

Upvotes: 5

Views: 218

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171491

This was a bug in G++ that discarded side-effects of expressions with type nullptr_t

It was fixed for G++ 4.7.4 and 4.8.0, see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52988 for an initial incomplete fix and http://gcc.gnu.org/bugzilla/show_bug.cgi?id=54170 for the complete fix.

Upvotes: 2

Related Questions