1

Why does placement new depend on #include <iostream>?

Sounds absurd? Well, this code only compiles if incommenting the include:

// #include <iostream>

struct Alignas { void* ptr; };

alignas(Alignas) static char storage[sizeof(Alignas)];

int main() { new(storage) Alignas; }

Gcc error (same with Clang):

alignas.cpp:7:27: error: no matching function for call to ‘operator new(sizetype, char [8])’
    7 | int main() { new(storage) Alignas; }
      |                           ^~~~~~~
<built-in>: note: candidate: ‘void* operator new(long unsigned int)’
<built-in>: note:   candidate expects 1 argument, 2 provided
<built-in>: note: candidate: ‘void* operator new(long unsigned int, std::align_val_t)’
<built-in>: note:   no known conversion for argument 2 from ‘char [8]’ to ‘std::align_val_t’

Looks like none of the candidates are the placement new. As if my placement-new expression isn't recognized. Unless I include that header, which is completely absurd, as it's a language feature.

EDIT:

It was absurd to me, as I've of course read the documentation on cppreference.com (which covers placement new), and the header deps listed there is none.

user2394284
  • 5,520
  • 4
  • 32
  • 38
  • 2
    It probably doesn't actually depend on ``. It probably depends on another header that your implementation of `` happens to include. Edit : Probably [``](https://en.cppreference.com/w/cpp/header/new). – François Andrieux Jun 26 '20 at 12:26
  • 2
    It probably requires `#include `, but I can't find a citation for that. *"which is completely absurd, as it's a language feature"* Language features depending on standard headers is not new, see `typeid`, `std::initializer_list`... – HolyBlackCat Jun 26 '20 at 12:28
  • As HolyBlackCat mentioned, it's part of ``. You can see the function definition in [`[new.syn]`](http://eel.is/c++draft/new.syn) from the standard. – ChrisMM Jun 26 '20 at 12:32
  • Placement new is a general mechanism to pass extra arguments to `operator new`. What you're talking about is the standard library use of placement new for constructing objects at a given location. That depends on the header file `` but placement new in general requires no header files. – john Jun 26 '20 at 12:33

1 Answers1

5

Why does placement new depend on #include <iostream>?

It doesn't. Placement new depends on <new>. And it depends on it because the language says that it depends on it. It has to do with operator new overloads which are called by placement new and are declared in <new>.

<iostream> just happened to include <new> for you. Which you should not rely on, of course.

user2394284
  • 5,520
  • 4
  • 32
  • 38
eerorika
  • 232,697
  • 12
  • 197
  • 326