文章目录
Problem
If you ever write the following code:
char* getStr()
{
return "hello world\n";
}
int main(int argc, char* argv[])
{
char* p = getStr();
return 0;
}
Compiling with GCC, you gonna get the following warning:
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
So what seems problem here?
Basic meaning and syntax
Both keywords can be used in the declaration of objects as well as functions. The basic difference when applied to objects is this:
-
const
declares an object as constant. This implies a guarantee that, once initialized, the value of that object won’t change, and the compiler can make use of this fact for optimizations. It also helps prevent the programmer from writing code that modifies objects that were not meant to be modified after initialization. -
constexpr
declares an object as fit for use in what the Standard calls constant expressions. But note that constexpr is not the only way to do this.
When applied to functions the basic difference is this:
-
const
can only be used for non-static member functions, not functions in general. It gives a guarantee that the member function does not modify any of the non-static data members. -
constexpr
can be used with both member and non-member functions, as well as constructors. It declares the function fit for use in constant expressions. The compiler will only accept it if the function meets certain criteria, most importantly:- The function body must be non-virtual and extremely simple: Apart from typedefs and static asserts, only a sin