【发布时间】:2011-04-06 11:57:19
【问题描述】:
常见情况:
- 将 std::string 传递给函数 foo(std::string*) 或 foo(std::string&);
- 将 tr1::shared_ptr 传递给函数 foo(tr1::shared_ptr* ptr) 或 foo(tr1::shared_ptr& ptr);
一般来说,什么是好的做法。我总是感到困惑。起初,将所有内容作为引用传递似乎是一致的,但是不可能将 Literals 作为引用传递或将 NULL 作为引用传递。
同样,将所有内容都作为指针似乎很好,但是我不得不担心指针可能指向 NULL,并在该函数的开头检查这些条件。
你觉得下面这个sn-p好不好?
#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;
}
谢谢 阿杰
【问题讨论】:
-
foo(tr1::shared_ptr<string>* ptr)在我看来,从好的设计的角度来看,这似乎是非常错误的。你知道常量引用吗? -
为什么不立即将
myFriends放入智能指针中? -
我认为这是How to pass objects to functions in C++? 的副本,我已经回答了一般问题。
-
你也不能使用
shared_ptr(或new),看我的回答...
标签: c++