常见情况:
- 将std::string传递给函数foo(std::string*)或foo(std::string&)。
- 将tr1::shared_ptr传递给函数foo(tr1::shared_ptr* ptr)或foo(tr1::shared_ptr& ptr)。
通常情况下,什么做法是好的?我总是感到困惑。一开始,把所有东西都作为引用传递似乎很一致,但无法将文字量或空指针作为引用传递。
同样,将所有东西作为指针也很好,但我必须担心指针可能指向NULL,并在该函数开头检查这些条件。
你认为以下代码片段是否好?
#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;
}
感谢 Ajay
foo(tr1::shared_ptr<string>* ptr)
从我看来,这个设计非常不好。你了解常量引用吗? - Anycornshared_ptr
(或者new
),请看我的回答... - Matthieu M.