Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a const reference to a const pointer?

Probably a conceptual mistake from my part but let's say I have a function which takes a char * as a parameter; that is, a C-style string. But I want to make sure that char * is pointing to something. So could I use something like:

foo(const char * const &cstring)

to specify that I'm expecting cstring to be a const reference to a const char *? This way I wouldnt need to check for NULL pointers inside foo.

like image 519
Gabriel C. Avatar asked Mar 04 '26 13:03

Gabriel C.


1 Answers

What you've written assures that the reference itself is bound to a valid pointer that may still be null. There isn't any compile time way to do what you want.

Your best option to to not use C-strings but take a std::string by value or const reference. If that isn't suitable then take the const char*, put in the function documentation that null is not accepted, and do a runtime assert that the pointer isn't null.

like image 80
Mark B Avatar answered Mar 06 '26 01:03

Mark B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!