Passing references to functions to be assigned to pointers in C++, Which way is better? -
i'm wondering 1 better of these 2 implementations of passing addresses pointers. there data exchange in 1st 1 doesn't happen in 2nd one? second 1 more efficient way? more readable? both same?
version 1
void ptrfunction(int& arg) { int* ptr = &arg; std::cout<<"the pointer's value:" << *ptr << "\n"; } int main() { int x=5; ptrfunction(x); return 0; }
version 2
void callviapointers(int *arg) { int *ptr = *arg; std::cout << "the pointer's value: " << *ptr; } int main() { int x = 100; callviapointers(&x); return 0; }
in terms of efficiency, 2 compile down same code behind-the-scenes, references implemented automatically-dereferenced pointers. perspective, 2 solutions equivalent.
as whether pass pointer or reference, that's judgment call depends on situation. if you're trying print out pointer integer (as you're doing here), pass-by-pointer makes bit more sense because it's more explicitly aligned you're trying do. in general, write function parameter of type want internally. if need pointer - either because you're building linked structure or because you're doing sort of memory allocation - take in pointer. if you're dealing polymorphic classes, traditionally accept argument pointer rather reference, though both work. if you're taking in stack-allocated object try modify it, reference can bit clearer. and, if you're in 1 of situations must use reference - example, parameter overloaded operator, copy constructor, or assignment operator - of course go reference. readability undervalued these days, making effort have clean, readable, intuitive code worth effort.
Comments
Post a Comment