如何初始化和访问 const char* const*

How to initialise and access a const char* const*

我看到一段 C++ 代码,其中的结构定义如下,带有奇怪的 const char* const*

struct TestStruct {
    const char* const* text; 
    void* data;
};

我需要使用上面的结构和 return 它的一个对象从一个函数。但是为此如何将 text 变量初始化为常量字符串?另外,如何从调用函数访问 text 指向的字符串。

TestStruct TestFunction() {
    TestStruct struct_obj;
    // TODO: how to assign struct_obj.text 
}

int main() {
    TestStruct struct_obj = TestFunction();
    // TODO: how to access struct_obj.text
}

你不能给常量变量赋值,但是你可以初始化这样的变量:

TestStruct TestFunction() {
    static const char* string = "hello world";

    TestStruct struct_obj = {
        &string,  // The text member
        nullptr   // The data member
    }
    return struct_obj;
}

常量是 immutable,所以不能赋值给它们。它们只能被初始化。对于 return 这样一个来自函数的结构,您可以使用聚合初始化(花括号初始化)。这个结构可以用任何char**初始化,但是访问它的人只能从char**中读取,而不能修改它。

TestStruct TestFunction() 
{
    char** lines = new char*[2];
    // Work with char** stored in lines
    *(lines + 0) = new char[10];
    *(lines + 1) = new char[20];
    void* data = nullptr;
    return TestStruct{ lines , data };
}

int main()
{
   TestStruct my_struct = TestFunction();
   // const char* const * means it's an immutable array of immutable CStrings
   const char* line_one = *my_struct.text;
   const char* line_two = *(my_struct.text + 1);
  
   std::cout << line_one << std::endl;
   std::cout << line_two << std::endl;
}

编辑: 我决定进一步澄清一下。

"const char* const *" 表示指向 immutable table 字符串的指针引用。 这意味着引用本身可以随时更改为引用其他 table。 constness 的最高级别是“const char * const * const”,读作 A pointer-constant-reference to an immutable table。指针常量引用意味着它不能指向任何其他 table 一旦构造并且如果这是一个结构的成员它肯定需要聚合初始化或至少默认构造


TestStruct struct_obj;
...
(char*&)struct_obj.text = "works";