warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

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

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值