I'm playing with some examples of C++.
I try to give two classes access to the same queue. This is the code:
#include <iostream>
#include <queue>
using namespace std;
class MessageQueue{
public:
std::queue<int> m_queue;
};
class A_Object{
public:
MessageQueue *ToMQ=0;
};
class B_Object{
public:
MessageQueue *FromMQ=0;
};
void connectMQ(MessageQueue *original, MessageQueue *source, MessageQueue *destination);
void connectMQ(MessageQueue *original, MessageQueue *source, MessageQueue *destination){
source = original;
destination = original;
// source and destination has the same addresses as original
}
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
MessageQueue *messageQueue1Send;
messageQueue1Send = new MessageQueue();
A_Object a_Object;
B_Object b_Object;
connectMQ(messageQueue1Send, a_Object.ToMQ, b_Object.FromMQ);
// at this point the addresses of a_Object.ToMQ and b_Object.FromMQ dont show to the same adress on the heap like messageQueue1Send
messageQueue1Send->m_queue.push(10);
int value = b_Object.FromMQ->m_queue.front();
cout << "value="<< value << endl;
return 0;
}
After the method connectMQ
, the addresses are not the same. It looks like the assignments of connectMQ
are only valid inside the method body.
How to make the assignments in the right way, to resolve this error and access only the heap address, not the stack?
In this code
void connectMQ(MessageQueue *original, MessageQueue *source, MessageQueue *destination){
source = original;
destination = original;
// source and destination has the same addresses as original
}
you have copies of the input arguments. Changing source does nothing to the callers variables. If you want to change source
and destintation
then do this
void connectMQ(MessageQueue *original, MessageQueue **source, MessageQueue **destination){
*source = original;
*destination = original;
// source and destination has the same addresses as original
}
called like this
connectMQ(messageQueue1Send, &a_Object.ToMQ, &b_Object.FromMQ);