如何在函数中传递const变量?

时间:2017-08-27 04:04:39

标签: c++ const

似乎函数传递的参数无法维护其const属性。 假设我需要使用函数中参数的信息初始化const变量,然后创建一个数组类型。我该怎么办?

示例:

#include <array>
using namespace std;

void foo(const int info)
{
    const int num = info + 1;  // seems num cannot be constant
    array<int, num> arr;
}

编译错误:

test.cpp: In function ‘void foo(int)’:
test.cpp:8:16: error: the value of ‘num’ is not usable in a constant expression
 array<int, num> arr;
            ^
test.cpp:7:15: note: ‘num’ was not initialized with a constant expression
     const int num = info + 1;  // seems num cannot be constant
               ^

更新: 使用数组类型会导致这样的麻烦,但使用简单类型数组就可以了:

void foo(int info)
{
    int array[info];
}

在编译期间是不是应该分配info

3 个答案:

答案 0 :(得分:1)

在C ++中,constconstexpr之间存在差异:Difference between `constexpr` and `const`

在您的情况下,您正在尝试创建一个编译时大小的数组,这需要constexpr。 constexpr不能简单地是const变量函数参数。您可以改为使用constexpr,也可以使用vector(运行时大小的数组)而不是array

答案 1 :(得分:1)

如果使用gcc -pedantic进行编译,您将看到int array[info]也不是标准C ++。请参阅the GCC docs

实现问题目标的一种方法是非类型模板参数:

#include <array>

template<int info>
void foo()
{
    constexpr int num = info + 1;
    std::array<int, num> arr; // or int arr[num]
}
// Call as foo<3>()

答案 2 :(得分:0)

如果你需要一个动态大小的数组,并且你不需要std :: array的特定属性,你可以使用vector。

主要区别是:

  

std :: array是一个封装静态大小的模板类   数组,存储在对象本身内,这意味着,如果你   在堆栈上实例化类,数组本身就会在   堆。它的大小必须在编译时知道(它作为一个传递   模板参数),它不能增长或缩小。

然而,向量内部存储在堆上。

来自:https://stackoverflow.com/a/4424658/128581

如果类型T可以轻易复制,那么进一步的std :: array是可以轻易复制的(这意味着你可以将它从一个地方存储到另一个地方而不必担心)。

使用矢量,如:

void foo(size_t size)
{
  vector<int> arr(size);
}