Jump to content
  • Advertisement
Sign in to follow this  
matches81

weird thing about T** and const T**&

This topic is 3613 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi there! I just ran into a weird issue. I wrote a function that returns a T** and want to pass the result into another function, which accepts const T**& as a parameter. Doing this, I get an error saying this conversion loses qualifiers. The simplest case I can come up with that causes this compiler error is something like this:
float* f = new float(10.f);
const float*& ref = f;
I know I can't lose a const in an assignment... but I don't see where I lose a const qualifier. This works, though:
float* f = new float(10.f);
const float* const &ref = f;
So, const-ing the pointer, too, seems to fix the issue... why do I have to const that pointer? Just curious, though, it's not a pressing matter.

Share this post


Link to post
Share on other sites
Advertisement
Consider the following program, pretending it compiled:

int main() {
float* ptr = 0;
const float*& ptr_ref = ptr;

const float f = 42.0f;
ptr_ref = &f;
*ptr = 42;
}



What would the last line try to do to the constant variable, f?

Your compiler is trying to protect you from accidentally doing this. HTH.

Share this post


Link to post
Share on other sites
Okay, I'll try to follow that example:

int main() {
float* ptr = 0;
const float*& ptr_ref = ptr;

const float f = 42.0f;
ptr_ref = &f; // this would ptr to the address of f
*ptr = 42; // this would effectively assign a new value to f, killing the constness of f
}


In the end, this way I'd get a float* pointing to a const float, correct?
Thx for the help.

Share this post


Link to post
Share on other sites
Bingo (and no problem). C++ says that modifying variables declared as const like this is undefined behavior, and may explode. The compiler tends to place constant literals like this in read only memory (in which case this kind of code WILL explode), or actually inline the data into the instruction stream -- placing multiple copies all over the place (this is especially true for any constant initialized to zero, which will likely get replaced with an xor instruction -- in this case, it will probably explode, but it could also just modify one copy).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!