int *转换为常数数组 [英] int* to Constant Array
问题描述
我问了这个问题:等效于裸字符串的数组
不能为const int*
提供此功能.真令人失望.所以我的问题是:在实践中,我如何解决这个限制?
To which the answer was C++ doesn't provide this functionality for const int*
s. Which is disappointing. So my question then is: In practice how do I get around this limitation?
我想写一个这样的结构:
I want to write a struct like this:
struct foo{
const char* letters = "abc";
const int* numbers = ???
};
我不能:
-
&{1, 2, 3}
因为我不能使用r值的地址 -
array<int, 3>{{1, 2, 3}}.data()
导致初始化后立即清理内存 -
const int* bar(){ return new int[3]{1, 2, 3}; }
不会导致删除该指针
&{1, 2, 3}
cause I can't take the address of an r-valuearray<int, 3>{{1, 2, 3}}.data()
cause the memory is cleaned up immediately after initializationconst int* bar(){ return new int[3]{1, 2, 3}; }
cause nothing will delete this pointer
我知道我可以使用自动指针解决此问题.我并不是在建议struct foo
是好的代码,我试图说明编译器已准备好将const数组"abc"
存储在内存中,并在程序退出时进行清理,我希望有一种方法也适用于int
.
I know that I can use an auto pointer to get around this. I am not suggesting that struct foo
is good code, I am trying to illustrate that the compiler makes a provision to store the const array "abc"
in memory and clean it up on program exit, I want there to be a way to do that for int
s as well.
有没有办法做到这一点?
Is there a way to accomplish this?
推荐答案
您指向的静态代码怎么样-我认为无论如何编译器内部都会为"strings literals"
做些什么?
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;
};
这篇关于int *转换为常数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!