2

我问了这个问题:Array Equivalent of Bare-String

答案是 C++ 没有为const int*s 提供这个功能。这是令人失望的。所以我的问题是:在实践中我如何绕过这个限制?

我想写一个这样的结构:

struct foo{
    const char* letters = "abc";
    const int* numbers = ???
};

我不能:

  1. &{1, 2, 3}因为我无法获取 r 值的地址
  2. array<int, 3>{{1, 2, 3}}.data()导致初始化后立即清理内存
  3. const int* bar(){ return new int[3]{1, 2, 3}; }因为什么都不会删除这个指针

我知道我可以使用自动指针来解决这个问题。我并不是说这struct foo是好的代码,我试图说明编译器规定将 const 数组"abc"存储在内存中并在程序退出时清理它,我也希望有一种方法可以为ints 做到这一点。

有没有办法做到这一点?

4

3 回答 3

6

How about a static which you point to - I think this what the compiler pretty much does internally for "strings literals" anyway?

static const int Numbers[] = {1, 2, 3};

struct foo{
    const char* letters = "abc";
    const int* numbers = Numbers;
};
于 2015-04-24T13:25:33.380 回答
2

字符串文字就是你所得到的。但是,它们也足以涵盖大多数积分数据。在您的情况下,您可以使用

L"\1\2\3"

得到一个编译器管理的宽字符数组。C++11 及更高版本还支持u8u16u32字符串。

于 2015-04-24T13:26:52.153 回答
1

我们可以使用Ben Voigt的回答来实现这一点:

const int* numbers = sizeof(int) == sizeof(char32_t) ? reinterpret_cast<const int*>(U"\1\2\3") : reinterpret_cast<const int*>(u"\1\2\3");

编译出三元组,您可以声明numbersconstexpr.

这种实现有几个缺点:

  1. 这实际上是一个wchar_t字符串文字,除了您指定的任何字符之外,您还将获得一个终止的 0 元素
  2. 这假设 aint将是 32 位或 16 位,如果不是这种情况,这将尝试从 achar16_t转换为任意大小int,您将遇到重大问题

在任何情况下,我们都可以将其简化为宏:

#define QUOTATION(x) sizeof(int) == sizeof(char32_t) ? reinterpret_cast<const int*>(U ## x) : reinterpret_cast<const int*>(u ## x)

可以像这样使用:

const int* numbers = QUOTATION("\1\2\3"); 
于 2015-04-24T14:46:47.650 回答