choxsword
choxsword

Reputation: 3359

Why does the implicit declaration does not introduce the name?

I've read the following two earlier questions,but still can't have a good undertanding.
1. Why do I need to #include when using the typeid operator?
2. When is #include library required in C++?

Since the typeid uses the type_info class,it's reasonable to require us #include<typeinfo>. However,the new operators also uses std::bad_alloc ,why does it not require us to #include <new>? ( I know that sizeof() does not require <cstddef> because the size_t coulde be replaced with built-in types during compile time,as long as the compiler knows what the size_t actually is. )

According to the most-voted answer in the 2th question,he says:

Note: the implicit declarations do not introduce the names std, std::bad_alloc, and std::size_t, or any other names that the library uses to declare these names. Thus, a newexpression, delete-expression or function call that refers to one of these functions without including the header is well-formed. However, referring to std, std::bad_alloc, and std::size_t is ill-formed unless the name has been declared by including the appropriate header.

The paragraph above is confusing,since everytime we use a type,we need to declare a type before usage like class A;void foo(A*);And the implicit declaration of void* operator new(std::size_t) throw(std::bad_alloc);also has a type std::bad_alloc ,is it a privilege for the implicit declaration to not declare the type it use?

Upvotes: 3

Views: 222

Answers (1)

xskxzr
xskxzr

Reputation: 13040

Forward declaration is used for name lookup. For the implicit declarations, the compiler already knows the semantic of these names, so it does not need to perform name lookup, thus a forward declaration (i.e. the header) is needless.

The key is that void foo(A*); is written by you, so you must tell the compiler what A is via a forward declaration, while the implicit declaration is written by the compiler, so you needn't tell the complier what the names used in the declaration are.

Note the reasons above are not sufficient to explain why <typeinfo> is required before any use of typeid. In fact, this rule is explicitly stated in the standard [expr.typeid] paragraph 6:

If the header <typeinfo> is not included prior to a use of typeid, the program is ill-formed.

Upvotes: 1

Related Questions