昨天在看mesos 0.10版本的代码时,看到如下的一段代码,对其中的一对{}
表示好奇。
{
flags::Flags<logging::Flags, master::Flags> flags;
flags.load(configuration.getMap());
master = new Master(_allocator, flags);
}
这段代码存在一个函数当中,并且前后都没有if\else或者while语句,可以说是毫无征兆的出现了这段代码。根据以前学习到的知识知道flags
变量的作用域是在这个范围之内的,在个这个{}
范围之外就不可以访访问到了,但是,我很好奇开发者为什么要这么写。然后,看了整个文件中的代码之后,一下子明白了作者的用意。该段代码所在的程序的文件为src/local/local.cpp:
#include <map>
#include <sstream>
#include <vector>
#include <stout/fatal.hpp>
#include <stout/foreach.hpp>
#include "local.hpp"
#include "configurator/configuration.hpp"
#include "configurator/configurator.hpp"
#include "detector/detector.hpp"
#include "logging/flags.hpp"
#include "logging/logging.hpp"
#include "master/dominant_share_allocator.hpp"
#include "master/master.hpp"
#include "slave/process_based_isolation_module.hpp"
#include "slave/slave.hpp"
using namespace mesos::internal;
using mesos::internal::master::Allocator;
using mesos::internal::master::DominantShareAllocator;
using mesos::internal::master::Master;
using mesos::internal::slave::Slave;
using mesos::internal::slave::IsolationModule;
using mesos::internal::slave::ProcessBasedIsolationModule;
using process::PID;
using process::UPID;
using std::map;
using std::string;
using std::stringstream;
using std::vector;
namespace mesos {
namespace internal {
namespace local {
static Allocator* allocator = NULL;
static Master* master = NULL;
static map<IsolationModule*, Slave*> slaves;
static MasterDetector* detector = NULL;
......
PID<Master> launch(const Configuration& configuration, Allocator* _allocator)
{
int numSlaves = configuration.get<int>("num_slaves", 1);
bool quiet = configuration.get<bool>("quiet", false);
if (master != NULL) {
LOG(FATAL) << "Can only launch one local cluster at a time (for now)";
}
if (_allocator == NULL) {
// Create default allocator, save it for deleting later.
_allocator = allocator = new DominantShareAllocator();
} else {
// TODO(benh): Figure out the behavior of allocator pointer and remove the
// else block.
allocator = NULL;
}
{
flags::Flags<logging::Flags, master::Flags> flags;
flags.load(configuration.getMap());
master = new Master(_allocator, flags);
}
PID<Master> pid = process::spawn(master);
vector<UPID> pids;
flags::Flags<logging::Flags, slave::Flags> flags;
flags.load(configuration.getMap());
for (int i = 0; i < numSlaves; i++) {
// TODO(benh): Create a local isolation module?
ProcessBasedIsolationModule* isolationModule =
new ProcessBasedIsolationModule();
Slave* slave = new Slave(flags, true, isolationModule);
slaves[isolationModule] = slave;
pids.push_back(process::spawn(slave));
}
detector = new BasicMasterDetector(pid, pids, true);
return pid;
}
.....
} // namespace local {
} // namespace internal {
} // namespace mesos {
省略了其中的一部分代码,注意其中的48行的全局变量的master和82行的flags变量,发现在同一个函数中有两个flags变量,73行和82行都有一个flags变量,按照语法规则来说这是不可以的,但是因为这里面的{}
将两个flags变量的各自的作用域隔离了,所以这两个flags变量并不会冲突。而且,今天在看leveldb的源代码的时候,同样也看到这种使用方法。