A const behavior I don't understand

B

Ben Thomas

Hello,

I have the following code which I don't understand why it works :

#include <iostream>
using namespace std;

void DontWork (unsigned int& i) {
cout << i << endl;
}

void Work (unsigned int const& i) {
cout << i << endl;
}

void main () {
signed int i = 1;
// DontWork (i);
Work (i);
}

What I don't understand is why the compiler can find an implicit
conversion when I add the const modifier, but it is unable to do so
without it.

(I know I should not code like this, but I just want to understand the
behavior.)

Thank you,
Ben.
 
B

Ben Thomas

Thanks Mike for the clarification, I understand why it works/don't works
now.

Ben.
 
T

Triple-DES

Hello,

I have the following code which I don't understand why it works :

#include <iostream>
using namespace std;

void DontWork (unsigned int& i) {
        cout << i << endl;

}

void Work (unsigned int const& i) {
        cout << i << endl;

}

void main () {
        signed int i = 1;
        // DontWork (i);
        Work (i);

}

What I don't understand is why the compiler can find an implicit
conversion when I add the const modifier, but it is unable to do so
without it.

In the process of converting from 'int' to 'unsigned int' a temporary
object is created. You cannot bind a non-const reference to a
temporary object.

Consider the example:
#include <iostream>
int main ()
{
int i = 1;
// fails: binding a non-const ref to a temporary
unsigned& uref = i;

// ok, binding const ref to temporary
const unsigned& curef = i;

i = 2;
if( i != curef)
std::cout << "curef is not bound to i";
}

You may think that the reference curef is bound to i, but it is not,
it is bound to an unnamed temporary object, as illustrated by the
example.

DP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top