3

Under gcc (and possibly other compilers) it is possible to write:

auto t = new decltype(nullptr);

I'm not sure what this does. Does that allocate memory for an object of type nullptr_t?

My question is not about the type of nullptr that is nullptr_t , my question is how does new nullptr_t() make sense ?

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Hassen Dhia
  • 555
  • 4
  • 11
  • *Does that allocate memory for an object of type nullptr_t?* Yes. – DeiDei Feb 08 '18 at 05:47
  • 1
    @Hassen: It makes sense in the exact same way that `new int{};` makes sense. Objects are *objects*, and you can create instances of objects with `new`. What's your confusion? – Nicol Bolas Feb 08 '18 at 06:04

3 Answers3

3

Does that allocate memory for an object of type nullptr_t?

Yes.

my question is how does new nullptr_t() make sense ?

From a syntactic point of view, there is nothing wrong with that.

From a semantic point of view, I can't see any sensible use case for it. All instances of nullptr_t are essentially the same from a usage point of view.

But then, someone might come up with a good use case that we have not been exposed to yet.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

my question is how does new nullptr_t() make sense ?

How does this make sense:

struct S
{
};

auto ptr = new S{};

This makes just about as much sense as dynamically allocating a nullptr_t instance. S has no contents, so it has no state outside of its address (two objects of the same type cannot have the same address, usually). So most functions that take an S can take any S instance and yield the same result. Oh yes, nullptr_t has a few more bells and whistles on it, but it is mostly an object type that is distinct from all other object types.

Sure, generally speaking you wouldn't do this deliberately. But if you're in template code, and someone passes nullptr_t as a template parameter, why would you want to make code that does new T{}; fail to compile? It doesn't hurt anything.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
1

If you remove the syntactic sugar, the satement becomes:

std::nullptr_t* t = new std::nullptr_t;

So this just a valid pointer of memory that points to something that is the sizeof std::nullptr_t;