C ++创建一个带有字符串:: size的数组 [英] c++ create an array with string::size

查看:70
本文介绍了C ++创建一个带有字符串:: size的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用string :: size成员创建一个数组,但是它在声明 char message [msgSize]时抱怨表达式未求值为常量。

Im trying to create an array with the string::size member but its complaining at the declaration of "char message[msgSize]" that the expression did not evalute to a constant.

但是我却不得不声明 msgSize。

However it alows me to declare "msgSize".

这怎么可能?为什么我允许创建一个常数,但不允许我将其用于需要const的东西。

How can this be? Why am i allowed to make a constant but i'm not allowed to use it to something that needs a const.

如果答案是:字符串可能会更改,则可以使用sizeof()进行相同的参数设置,但可以使用。

If the answer is that: "the size of the string could change" then the same argument can be made for using sizeof(), but that works.

const unsigned int msgSize = 
        saveAs.size() +
        sizeof("NOTE|  sent get request to: ") + 10;

    char message[msgSize];
    memset(message, 0, msgSize);
    sprintf_s(message, msgSize,"NOTE| sent get request to: %s", saveAs.c_str());
    _cRec->output(message);


推荐答案

const 仅表示您保证该值不会更改。您甚至可以使用 const_cast 覆盖它。

Well const just means that you promise that the value won't change. And you can even override that with a const_cast.

编译器所需的值可以在编译时间。这是一个更严格的要求。此类值用 constexpr 关键字标记。

What compiler needs there is a value that can be evaluated at the compile time. This is a stronger requirement. Such values are marked with constexpr keyword.

不幸的是,您对 std感到不走运:: string ... size()不是 constexpr

Unfortunately you are out of luck with std::string... size() is not a constexpr.

我在 玩过以下示例

#include <iostream>
#include <string>
using namespace std;

const string msg("Some msg");
constexpr int msg_len = msg.size();

int main() {

    char msg[msg_len];

    cout << sizeof(msg);
    return 0;
}

问题是 size()不是 constexpr ,并且不能将 string 做成 constexpr ,因为它具有非平凡的析构函数。

The thing is that size() is not a constexpr, and you cannot make string a constexpr because it has a non-trivial destructor.

为什么以这种方式设计它已经超出了我的范围。似乎是一种直觉和严重的限制。但是, string 的实现非常巧妙,例如,通过小型存储优化。在实现上没有进行重大更改的情况下,可能很难使它们成为 constexpr

Why it is designed this way is beyond me. Seems like a counter intuitive and serious limitation. However, there are pretty clever implementation of string, for example with small storage optimization. It might be hard to make them constexpr with out serious changes in the implementation.

这篇关于C ++创建一个带有字符串:: size的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆