Search code examples
c++gccc++14nullptr

Constructor that takes nulltpr_t: function definition does not declare parameters


I have the following code:

class C {
private:
    void *data;

public:
    constexpr C(nullptr_t) : data(nullptr) { }
    C(int i) : data(new int(i)) { }
};

I have created a constructor which takes nullptr_t, so that I can have code similar to the following:

C foo(2);
// ...
foo = nullptr;

Code similar to this has worked previously on MSVC, however this code fails to compile on GCC 5.3.1 (using -std=c++14) with on the closing bracket of C(nullptr_t) with error: function definition does not declare parameters. Even if i give the parameter a name (in this case _), I get error: expected ')' before '_'. This also fails if the constexpr keyword is removed.

Why am I unable to declare such a constructor, and what are any possible workarounds?


Solution

  • You must be a fan of "using namespace std", and you just got tripped up by it:

    constexpr C(std::nullptr_t) : data(nullptr) { }
    

    gcc 5.3.1 compiles this, at --std=c++14 conformance level:

    [mrsam@octopus tmp]$ cat t.C
    #include <iostream>
    
    class C {
    private:
        void *data;
    
    public:
        constexpr C(std::nullptr_t) : data(nullptr) { }
        C(int i) : data(new int(i)) { }
    };
    [mrsam@octopus tmp]$ g++ -g -c --std=c++14 -o t.o t.C
    [mrsam@octopus tmp]$ g++ --version
    g++ (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6)
    Copyright (C) 2015 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.