Return a read-only double pointer
Asked Answered
C

3

5

I want to a member variable, which is a double pointer. The object, the double pointer points to shall not be modified from outside the class.

My following try yields an "invalid conversion from ‘std::string**’ to ‘const std::string**’"

class C{

public:
    const std::string **getPrivate(){
        return myPrivate;
    }

private:
    std::string **myPrivate;
};
  • Why is the same construct valid if i use just a simple pointer std::string *myPrivate
  • What can i do to return a read-only double pointer?

    Is it good style to do an explicit cast return (const std::string**) myPrivate?

Canonicals answered 8/6, 2011 at 18:45 Comment(4)
Sorry for not being clear, i edited my post. Its the string itself that shall not be modified.Canonicals
Thinking of them as "double pointers" may be the root of your problem. The term "double pointer" is one I never encountered until I came across SO, and I'd be kind of interested to know which nitwit (not necessarily on SO) originated it.Graehl
Also, with regards to your last sentence, it's rarely good style to do an explicit cast. Casting may be necessary but is never stylish.Pseudohermaphroditism
A "double pointer" is not a thing in C++. What you're playing with here is a "pointer to pointer".Rushton
A
3

Try this:

const std::string * const *getPrivate(){
    return myPrivate;
}

The trouble with const std::string ** is that it allows the caller to modify one of the pointers, which isn't declared as const. This makes both the pointer and the string class itself const.

Agonic answered 8/6, 2011 at 19:37 Comment(0)
A
2

If you want to be really picky :

class C {

public:
    std::string const* const* const getPrivate(){
        return myPrivate;
    }

private:
    std::string **myPrivate;
};
Astoria answered 8/6, 2011 at 19:43 Comment(0)
E
2

There are very rare cases in c++ when a raw pointer (even less for a double pointer) is really needed, and your case doesn't seams to be one of them. A proper way would be to return a value or a reference, like this :

class C{

public:
    const std::string& getPrivate() const
    {
        return myPrivate;
    }

private:
    std::string myPrivate;
};
Euchologion answered 8/6, 2011 at 19:49 Comment(2)
This would have been my preferred way as well - especially with a string, but I didn't know if the poster had some other type that might have actually required this...Agonic
Perhaps i should have written my Motivation: I want to have access to an array with two indices x[0][1], so i created an array of pointers. But although it might have been possible to change my code in another position i wanted to know how to handle "double-pointers" or hower a pro calls pointers-to-pointers.Canonicals

© 2022 - 2024 — McMap. All rights reserved.