VP.
VP.

Reputation: 16765

What are the differences between anonymous namespace and anonymous scope in c++?

What is the difference between:

namespace {
    // code
} // anonymous namespace

and

{
    // code
}

I understand that:

  1. We can't write namespace inside a function
  2. We can't write anonymous block outside a function
  3. Anonymous namespaces have long life, they can be extended; anonymous scopes dont, everything is destroyed when it leaves the scope.

Do I miss something?

Upvotes: 1

Views: 279

Answers (3)

utnapistim
utnapistim

Reputation: 27385

namespace {} creates a namespace (a space for names) that changes how the declarations inside will be found by the compiler (in this case, it is an anonymous namespace, meaning that symbols declared inside are accessible only in the current compilation unit).

{} creates a scope (a block of executable code) that isolates the statements inside, and changes how the code within the block will be executed.

The first matters to the compiler, the second matters at execution. They are completely different things.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234855

There are enormous differences.

Anything in an anonymous namespace is only visible to that compilation unit. (It's somewhat similar to one particular use of static). You can't put statements into anonymous namespaces.

{ } is a scoping block. It can contain statements.

Upvotes: 4

YSC
YSC

Reputation: 40150

There is a big difference: what is defined in an anonymous namespace still exists outside, although what's created inside a block dies with it ending.

Upvotes: 1

Related Questions