1

I have written functions to return const char* without any problem:

class Test {
public:
    const char* data() const {return data_;}
private:
    char* data_;
};

int main()
{
    Test test;
    const char* temp = test.data();

    return 0;
}

Today I need to return the const char**, so I did the same thing:

class Test {
public:
    const char** data() const {return data_;}
private:
    char** data_;
};

int main()
{
    Test test;
    const char** temp = test.data();

    return 0;
}

But it tells me:

main.cpp:15:39: error: invalid conversion from ‘char**’ to ‘const char**’ [-fpermissive]
     const char** data() const {return data_;}
                                       ^~~~~

In MSVC it reports:

error C2440: 'return': cannot convert from 'char **const ' to 'const char **'

I know it it because the the const char** is not "fully const", it is the pointer of const char*, but the error message is really confused how to fix it.

My question is: What's the correct way to return a "fully const" char**? Thanks!

zzy
  • 1,771
  • 1
  • 13
  • 48
  • 1
    What is the point of storing a `char **` as a member, and returning it to the caller? Typically double pointers are used by storing a `char*`, and using the address of it when a double pointer is required. Of course, in C++ you're rarely dealing with that in the first place, between reference semantics and `std::string` (or smart pointers in general) providing strictly better ways to solve problems like this. – ShadowRanger Jun 12 '19 at 01:53
  • @ShadowRanger Yes, can't agree you more, my problem is that an old interface need argc and argv like parameter. I store the char** as member so that I could use desctructor to free them then everyone could happy to use this old interface in a C++ way. My class wrapper now return the const char* and use & when passing to that interface, so I'm thinking whether it could be more beautiful. – zzy Jun 12 '19 at 02:19
  • You can convert to `const char *const *`—is that what you’re after? – Davis Herring Jun 12 '19 at 02:27
  • @DavisHerring Oh thanks, that's the grammar I'm looking for! – zzy Jun 12 '19 at 02:34
  • @GBrandt Thanks, it is so hard to search something includes **. That question is asking the samething. – zzy Jun 12 '19 at 02:35

0 Answers0