Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

gcc

c++11

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 {}; }
like image 731
Andrew Tomazos Avatar asked Nov 01 '22 15:11

Andrew Tomazos


1 Answers

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.

like image 62
Jonathan Wakely Avatar answered Nov 12 '22 23:11

Jonathan Wakely