-1

I have data, confined in a struct called transfer_data:

struct transfer_data{
    std::vector<int> data;
}

and I have vectors pointing on that data:

transfer_data dat1, dat2;
transfer_data *ptr_dat1 = &dat1, *ptr_dat2 = &dat2;

Now my function is fixed onto always reading data from a copy of one pointer, while the data belonging to the other one is processed in a second thread. When the data processing is finished, the first pointer is exchanged with the second one by the second thread.

I wanted to use that approach in order not to copy too much data (>1 Mbyte) around when the second thread is finished processing, and to avoid race conditions (first thread is reading, second thread is writing on the same place etc.). Thus by copying only vectors it should be way faster.

My problem is: How can I exchange non-global pointers in a function? If I want to do that for variables, I write

void switch(int &a, int &b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

When writing a similar thing for pointer:

void switch(int *a, int *b)
{
    int *tmp = a;
    a = b;
    b = tmp;
}

But if I am doing that, then I only switch the pointer values locally, and not globally, i.e. returning from the function means returning to status quo.
How can I fix my function? Or is there a more fundamental flaw in my approach?

arc_lupus
  • 3,942
  • 5
  • 45
  • 81
  • 5
    Make it passing by reference, as you did for `int`. `void switch(int *&a, int *&b)` – songyuanyao Sep 21 '16 at 09:14
  • @songyuanyao: That is the first time I see something like that (that combination of `*` and `&`). And that will only copy the pointer, and not the whole stuff the pointer is pointing at? – arc_lupus Sep 21 '16 at 09:16
  • Or by using ** (pointer to pointer), passed to the function. – Adrian Roman Sep 21 '16 at 09:17
  • By the way, there is a `std::swap`, there is no need to use that tmp intermediary now all over. – Adrian Roman Sep 21 '16 at 09:18
  • @arc_lupus No, it doesn't copy the pointee. To be precise, it doesn't copy pointer too, since it's reference. Anyway, principle is the same as `int&`. – songyuanyao Sep 21 '16 at 09:19

1 Answers1

1

By using references you can achieve this.

void switch(transfer_data* &a, transfer_data* &b)

The variables which are passed as arguments can now be altered inside the function now. When you are doing

void switch(transfer_data* a, transfer_data* b)

copies of variables which store the addresses are made and hence the original variables stay unaffected. A reference is basically an alias (nickname) for some variable, so by using a reference you can modify it within the function body.

If you want to read up on how references are actually implemented by the compiler here's a good starting point.

Community
  • 1
  • 1
nishantsingh
  • 4,537
  • 5
  • 25
  • 51