昨天在看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的源代碼的時候,同樣也看到這種使用方法。