文章目录
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:
-
constdeclares 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. -
constexprdeclares 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:
-
constcan 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. -
constexprcan 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 s

本文详细解释了C++中关于'constexpr'和'const'的区别和用法,以及如何在编译时遇到ISO C++警告时解决问题。讨论了它们在声明对象和函数时的作用,特别是在常量表达式中的应用,并给出了修正警告的建议。

3617

被折叠的 条评论
为什么被折叠?



