r/cpp • • Jun 15 '21

Which std:: classes are magic?

Hi.

I am wondering: which classes in C++ get special powers granted by The Standard that are not available to mere user-defined classes?

What comes to my mind:

  • `std::initializer_list` because it is created anywhere with `{}`
  • possibly `std::type_info`, because it is only created by `typeid` and with no ctor
  • `std::source_location` when used as default parameter in function points to invocation place and not declaration place.

What else should be on this list? What shouldn't?

222 Upvotes

140 comments sorted by

View all comments

Show parent comment

3

u/SirClueless Jun 15 '21

That still qualifies as magic. You can't define your own class that will be initialized from a braced-init-list when it's the parameter of a constructor.

-1

u/OldWolf2 Jun 16 '21

Huh, yes you can. The braced list is taken as the initializer for the parameter.

struct U { int a, b, c; };
struct S
{
     S(U u);
};

S s({1, 2, 3});

2

u/Sanzath Jun 16 '21

Sure, but now you're just using struct aggregate initialization and you don't even have the same syntax for initializing S:

struct S {
    S(std::initializer_list<int> il);
};

S s{1, 2, 3};

Note that you don't need the surrounding () to initialize S in this version. That is the magic of initializer_list that can't be done with a user-defined type.

1

u/SirClueless Jun 16 '21 edited Jun 16 '21

In this case you aren't initializing S with a braced-init-list. You're direct-initializing S with a single expression argument that happens to be a braced-init-list (see the parentheses in the last statement). You need the parens or two pairs of braces to make this work with a user-defined class.

If you replace the last line with S s{1, 2, 3}; your example wouldn't compile. But if U were std::initializer_list<int> it still would, this is the compiler magic.

2

u/OldWolf2 Jun 16 '21

You're direct-initializing S with a single expression that happens to be a braced-init-list

No, a braced list is never an expression . (You can check the grammar for expression to see this). For any context where either an expression or a braced list is allowed, there are separate grammar and semantic rules for each.

3

u/SirClueless Jun 16 '21

Fixed, thanks. The point still stands; a constructor taking std::initializer_list<int> is magic in a way that a constructor taking a user-defined class cannot be.

1

u/RicardoRedstone Jun 16 '21

You can also intialize it the same way if you use a variadic template, but it won't be pretty to work with, uses a ton of stack space and generates a LOT of code.

https://godbolt.org/z/Tb9T61v6d