首頁 > 後端開發 > C++ > 主體

在 C 中什麼時候應該使用引用還是指標?

Linda Hamilton
發布: 2024-11-13 12:26:02
原創
208 人瀏覽過

When Should I Use References vs. Pointers in C++?

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:

  • Modify the actual value of the passed variable.
  • Pass complex objects (e.g., strings, vectors) efficiently, avoiding the overhead of copying.

Pass by Pointer:

Passing by pointer is necessary when:

  • You cannot pass a temporary object by reference (since a reference must bind to an existing object).
  • You need to pass a null pointer.
  • You need to change the pointer itself, not its target (e.g., assign a new value to the pointer).

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板