常见情况:
一般来说,什么是好的做法.我总是感到困惑.首先,将所有内容作为引用传递似乎是一致的,但是不可能将Literals作为引用传递或将NULL作为引用传递.
类似地,将所有内容作为指针似乎都很好,但是我必须担心指针可能指向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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢Ajay
这是我之前关于在C++中返回引用的问题的后续问题:在c ++中返回对象的最佳方法?
我可以成功返回引用,但是,我无法阻止观察者完全覆盖有问题的变量.我使用了const引用,但我希望观察者能够改变值.
代码如下:
class Layer {
public:
Channel& getChannel();
private:
Channel channel;
};
// return reference to channel
Channel& Layer::getChannel() {
return channel;
};
// FINE
layer.getChannel().someMethod();
// BAD: PRIVATE MEMBER IS OVERWRITTEN
layer.getChannel() = Channel();
Run Code Online (Sandbox Code Playgroud)
现在我很确定要防止这个我必须改变函数的签名才能返回const引用,但是,我someMethod之后无法打电话:
// CHANGE TO CONST REFERENCE
Channel const& Layer::getChannel() {
return channel;
};
// return const ref of channel
Channel const& channel = layer.getChannel();
// ERROR!!
// 'Channel::someMethod' : cannot convert 'this' pointer from 'const Channel' …Run Code Online (Sandbox Code Playgroud) c++ ×2