Passing by Reference vs. Pointer in C++
In C++, understanding when to use references and pointers can be a confusing topic. This article explores the nuances of passing by reference and by pointer, providing practical guidelines.
Pass by Reference:
Passing by reference is recommended when you need to:
Pass by Pointer:
Passing by pointer is necessary when:
Best Practices:
As a general rule, prefer passing by reference whenever possible. However, when dealing with literals, null pointers, or situations where you need to modify the pointer itself, pass by pointer.
Example:
The code snippet provided passes a pointer to a dynamically allocated vector to a map. This is a valid approach because we need to both create a new vector and pass it by reference to the map. By using pointers, we avoid the need to copy the entire vector.
#include <iostream> #include <vector> #include <map> #include <string> #include <tr1/memory> #include <algorithm> using namespace std; using namespace std::tr1; int main(){ map<string, shared_ptr<vector<string>>> adjacencyMap; vector<string>* myFriends = new vector<string>(); myFriends->push_back(string("a")); myFriends->push_back(string("v")); myFriends->push_back(string("g")); adjacencyMap["s"] = shared_ptr<vector<string>>(myFriends); return 0; }
以上是在 C 中什麼時候應該使用引用還是指標?的詳細內容。更多資訊請關注PHP中文網其他相關文章!