Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange use of const - why does this compile?

Tags:

c++

gcc

I recently found the following function definition in some code I was reviewing:

void func( const::std::string& str )
{
    // Do something...
}

I am surprised that the const::std::string appears to be legal ( it compiles with GCC4.4, GCC 4.8, Clang 3.2 & Intel 13.0.1).

Does the standard specify that const can be used as a namespace?

like image 719
mark Avatar asked Apr 03 '13 08:04

mark


People also ask

What does a compiler do with const?

The compiler ensures that the constant object is never modified. You can call either constant or non-constant member functions for a non-constant object.

Does const make code faster?

No, const does not help the compiler make faster code. Const is for const-correctness, not optimizations.

Does const affect performance?

const correctness can't improve performance because const_cast and mutable are in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your const data may e.g. be a pointer to a std::atomic , meaning the compiler has to respect changes made by other threads.

What is the point of using const?

The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).


2 Answers

Does the standard specify that const can be used as a namespace?

No, it does not, because it can't be.

Your code is the same as:

void func( const ::std::string& str );

The first scope resolution operator denotes global namespace.

like image 71
jrok Avatar answered Nov 03 '22 02:11

jrok


It is parsed as

const ::std::string& str

where ::std::string is a valid way to refer to std::string.

like image 30
NPE Avatar answered Nov 03 '22 01:11

NPE