问题
"pointer" holds the address of "Int". I want to pass that address to my given classes by reference:
class N {
public:
N(int &pPointer){
std::cout << "Address: " << &(pPointer) <<" \n";
}
};
class M {
public:
M(int &pPointer):n(pPointer) {
std::cout << "Address: " << &pPointer <<" \n";
}
private:
N n;
};
int main () {
int Int = 5;
int *pointer = ∬
std::cout << "Address: " << pointer <<" \n";
M m(*pointer);
return 0;
}
Is this a good practice (since I'm kind of using a reference to a dereferenced pointer)? Or is it absolutely horrible? I simply want to avoid pointers here. (Although I'm forced to use "*pointer" in the beginning. )
回答1:
It's totally OK to pass by reference instead of passing by pointer to use the abject later, as lon you know the pointer you are using is valid. This allows you to skip the nullptr
check, because references can't be null.
However if you store a reference, you won't be able to replace the object being referred to, to another. But you can do that with a pointer.
You can, later, take the address of the referenced object, but do you really think you need to do that? Because you can use the reference instead
回答2:
It's ok if you must, but do consider using a constant reference N(const int& pPointer)
instead in the function parameters. This means you can't change the pointer to point at something else, but you could can still modify the underlying variable value with a dereference.
Also take care if you store the reference as a data member in the class. You could end up with a 'dangling reference' if the object in the caller (an int in your case) goes out of scope.
来源:https://stackoverflow.com/questions/16604374/passing-an-address-to-a-class-and-from-there-to-its-child-class-by-reference-i