Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a read-only double pointer

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?

like image 974
Hugo Avatar asked Jun 08 '11 18:06

Hugo


3 Answers

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.

like image 58
James Johnston Avatar answered Nov 08 '22 04:11

James Johnston


If you want to be really picky :

class C {

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

private:
    std::string **myPrivate;
};
like image 2
user703016 Avatar answered Nov 08 '22 04:11

user703016


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;
};
like image 2
BЈовић Avatar answered Nov 08 '22 03:11

BЈовић