0
#include <memory>

class K
{
public:
    static const int k = 4;
};


class C
{
public:
    C(int i)
    : _i(i)
    {}

private:
    int _i;
};

int main(int argc, char * argv[])
{
    C * pc = new C(K::k);

    auto uc = std::make_unique<C>(K::k);
}

The make_unique barfs on accessing K::k, and is explained in a number of questions, like here and here.

These answer why you need to define the value outside the class according to the standard. According to the standard it makes perfect sense.

My question is about why the standard specifies things this way.

Why doesn't it just work?

Is this simply a workaround for today's compilation systems?

Why doesn't the standard allow implementations to simply copy the value out of the header file if a value is specified in the header file?

Why aren't linkers required to track values specified in class declarations and create storage for them if necessary at link time?

This is a reasonably large impediment to convince people to replace new with std::make_unique if make_unique requires other hoops to jump through due to forwarding and references.

bizaff
  • 169
  • 7
  • "Why aren't linkers required to track values specified in class declarations and create storage for them if necessary at link time?" - because linkers are very, very stupid pieces of software, and always have been, People love writing compilers, they don't love writing linkers. –  Mar 28 '17 at 21:55
  • 2
    In C++17, if you declare `K::k` to be `constexpr`, the code will work. `K::k` would be implicitly an inline variable and the linker would do the right thing. – Brian Bi Mar 28 '17 at 22:00
  • @Brian: More generally, you would declare the static member `inline` (even if you want it mutable or dynamically initialized). – Kerrek SB Mar 28 '17 at 22:06
  • You could use an `enum` instead of static const int – M.M Mar 28 '17 at 22:51

0 Answers0