c++ - 当值是非常量但使用常量表达式初始化时使用 constexpr?

标签 c++ c++11 constexpr

出于某种原因,我很难掌握如何正确使用 constexpr

标题中描述的情况是否适合使用它?即:

void foo()
{
    static constexpr const size_t MAX_BUFFER_SIZE = 20 * 1024 * 1024;

    constexpr size_t bufferSize = 1024 * 1024; // Initialized with constant expression
    std::vector<char> buffer(bufferSize, ' ');

    //...

    if (some_condition())
    {
        bufferSize = get_random_value_at_runtime(); // Assigned a new 'non-constexpr' value
        buffer.resize(bufferSize, ' ');
    }

    //...   
}

亲切的问候!

最佳答案

Is the situation described in the title an appropriate place to use it?

错了。

constexpr size_t bufferSize = 1024 * 1024; // Initialized with constant expression

// ...

    bufferSize = get_random_value_at_runtime(); 

constexpr 暗示(也是)const

您不能重新分配 const 变量。

关于c++ - 当值是非常量但使用常量表达式初始化时使用 constexpr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53066712/

相关文章:

c++ - 分割数组更简单的方法是什么

c++ - 在微小的 Xml 元素中更新数据

c++ - 访问单例类 C++ 时遇到问题

c++11 - 用于存储 ipv4 或 ipv6 地址的最有效的 protobuf 类型(在 C++ 中)是什么?我的地址是 boost::asio::ip::address_v4(或 v6)

c++ - 警告 : function uses 'auto' type specifier without trailing return type

c++ - move 分配给自己的行为

c++ - 带有基类的 CRTP 试图获取派生类成员的返回类型 : invalid use of incomplete type

c++ - 如何在一行中通过指针构造一个点?

c++ - constexpr 构造函数是否允许 return 语句?

c++ - Constexpr 成员函数