指出该类的错误并改正 :class TraceHolder { public: TraceHolder() = delete; static void Register(const std::string& task_name) { auto &map = GetMap(); auto it = map.find(task_name); if (it == map.end()) { std::unique_ptr<StopWatch> ticker = std::make_unique<StopWatch>(); map[task_name] = std::move(ticker); return; } auto ticker = it->second; ticker->reset(); return; } static bool Tick(const std::string &task_name) { auto &map = GetMap(); auto it = map.find(task_name); if (it == map.end()) return false; auto ticker = it->second; ticker->getTime(); double val = ticker->getTime(); TLOGI("%s took %lf ms.", task_name.c_str(), val); return true; } static std::map<std::string, std::unique_ptr<StopWatch>()> &GetMap() { static std::map<std::string, std::unique_ptr<StopWatch>()> map; return map; } };
时间: 2024-01-16 18:05:11 浏览: 38
错误:
1. 在定义静态成员函数 GetMap() 时,应该返回一个引用类型的 map,但是现在返回的是一个指向 map 的 unique_ptr。
2. 在 Tick() 函数中,应该先调用 getTime() 函数获取计时器的时间,再输出日志,但是现在的代码中打印日志和获取时间的顺序颠倒了。
改正后的代码如下:
```
class TraceHolder {
public:
TraceHolder() = delete;
static void Register(const std::string& task_name) {
auto& map = GetMap();
auto it = map.find(task_name);
if (it == map.end()) {
std::unique_ptr<StopWatch> ticker = std::make_unique<StopWatch>();
map[task_name] = std::move(ticker);
return;
}
auto& ticker = it->second;
ticker->reset();
return;
}
static bool Tick(const std::string& task_name) {
auto& map = GetMap();
auto it = map.find(task_name);
if (it == map.end()) return false;
auto& ticker = it->second;
double val = ticker->getTime();
TLOGI("%s took %lf ms.", task_name.c_str(), val);
return true;
}
static std::map<std::string, std::unique_ptr<StopWatch>>& GetMap() {
static std::map<std::string, std::unique_ptr<StopWatch>> map;
return map;
}
};
```
相关推荐
![hpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)