Copying pointers in C++
I have a class A containing two pointers to objects of another class B. I want to initialize one pointer or the other depending on which one is passed to init()
, which also takes other parameters. My situation is thus the following:
class A {
public:
A();
init(int parameter, int otherParameter, B* toBeInitialized);
protected:
B* myB;
B* myOtherB;
};
Now my point is that I want to call init()
as:
init(640, 480, this->myB);
or
init(640, 480, this->myOther开发者_StackOverflow中文版B);
Now, my init is implemented as:
void init( int parameter, int otherParameter, B* toBeInitialized ) {
toBeInitialized = someConstructorFunction(parameter, otherParameter);
}
The problem is that the two pointers are not initialized, I suspect that toBeInitialized is overwritten, but the original parameter is not modified.
I am doing something wrong? Should I use references to pointers?
Thank you
TommasoYes, change to
void init( int parameter, int otherParameter, B*& toBeInitialized ) {
toBeInitialized = someConstructorFunction(parameter, otherParameter);
}
In your original code toBeInitialized
is passed by value and only the local copy of the variable will be modified.
This is obviously a cut-down problem, but as stated would it not be better to have something like this:
class A {
public:
A();
B* buildB(int parameter, int otherParameter);
protected:
B* myB;
B* myOtherB;
};
Then call the function as
this->myB = buildB(640, 480);
Converting the third parameter to be a reference to (or pointer to) the member would work, but it smells like your design might be wrong.
You are passing toBeInitialized
by value, so the value modified inside init()
is not reflected outside. You need to either pass reference to toBeInitialized
pointer or a double pointer. i.e. change init signature to
init(int, int, B*&)
or init(int,int,B**);
Consider using pointers to members. (it will give you a little more safety.)
void A::init(int p1, int p2, B * A::* memberToInit)
{
this->*memberToInit = SomeConstructorFunc(p1, p2);
}
And the usage would be
myObject.init(480, 620, &A::myB);
精彩评论