int* to Constant Array

偶尔善良 提交于 2019-12-11 03:48:34

问题


I asked this question: Array Equivalent of Bare-String

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 = ???
};

I cannot:

  1. &{1, 2, 3} cause I can't take the address of an r-value
  2. array<int, 3>{{1, 2, 3}}.data() cause the memory is cleaned up immediately after initialization
  3. const int* bar(){ return new int[3]{1, 2, 3}; } cause nothing will delete this pointer

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 ints as well.

Is there a way to accomplish this?


回答1:


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;
};



回答2:


String literals are all you get. However, they are also enough to cover most integral data. In your case you can use

L"\1\2\3"

to get a compiler-managed array of wide characters. C++11 and later also support u8, u16, and u32 strings.




回答3:


We can accomplish this using Ben Voigt's answer:

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

The ternary is compiled out as is evidenced by the fact that you can declare numbers as constexpr.

There are a couple drawbacks to this implementation:

  1. This is actually a wchar_t string literal you will get a terminating 0 element in addition to any characters you specify
  2. This assumes that an int will be either 32-bits or 16-bits, if that's not the case this will try to cast from a char16_t to a whatever sized int and you will have major problems

In any case we can simplify this into a macro:

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

Which can be used like:

const int* numbers = QUOTATION("\1\2\3"); 


来源:https://stackoverflow.com/questions/29848547/int-to-constant-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!