Ralf Fassel <
ral...@gmx.de> wrote:
> | This code works, but is it possible to implement fn2() it in one line,
> | without creating a temporary variable?
>
> I'd say
>
> void fn2(int &iref)
> {
> fn1(&iref, sizeof(int*));
> }
>
> should work...
But it's not the same.
I modified it:
#v+
void fn1(const void *p, size_t sz)
{
const unsigned char *b(static_cast<const unsigned char *>(p));
printf("Pointer value to be transferred:");
for (size_t i(0); i < sz; ++i)
printf(" %02x", b[sz - i - 1]);
printf("\n");
}
void fn2(int &iref)
{
int *iptr(&iref);
printf("Address of iptr: %p\n", &iptr);
printf("Address of iref: %p\n", &iref);
fn1(&iptr, sizeof(iptr));
fn1(&iref, sizeof(int*));
}
int main()
{
int i(0x12345678);
fn2(i);
return 0;
}
#v-
Running it gives:
#v+
Address of iptr: 0x7eb0c574
Address of iref: 0x7eb0c584
Pointer value to be transferred: 7e b0 c5 84
Pointer value to be transferred: 12 34 56 78
#v-
Addresses of iptr (temporary pointer) and reference (`i` in main) are
different (and should be), but only the first call to fn1 (where it reads
the temporary pointer) gives the proper address of `i` in main (address
that is recreated in another thread). Reading data pointed to by &iref
gives the value of `i` itself (which in this case is of the same size as
the pointer-to-i).
> In your fn2(), you are passing the address of the temporary _pointer_,
> not the address of the pass-by-reference-variable, which seems wrong to
> me. Instead it should be fn1(iptr, sizeof(iptr)).
Hmm... I need to read the temporary pointer contents, that is -- know what
it points to. After fn1() terminates, the pointer is not needed anymore,
because its contents has been transferred.
I don't want to transfer contents of `i`, I want to transfer its address.
`i` is modified in `main` and I need to see these changes in thread.
This is a simplified example, in reality `i` is not int, but a class.
--
https://www.youtube.com/watch?v=9lSzL1DqQn0