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
?
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.
If you want to be really picky :
class C {
public:
std::string const* const* const getPrivate(){
return myPrivate;
}
private:
std::string **myPrivate;
};
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;
};
精彩评论