gpt4 book ai didi

c++ - 在同一个类的静态函数中创建一个类的实例是未定义的行为吗

转载 作者:行者123 更新时间:2023-11-30 00:44:49 25 4
gpt4 key购买 nike

我所有的搜索在 C++ 解决方案方面收效甚微....
我有一个从配置文件中获取信息的类,我有一个静态函数可以从不同的配置文件中获取站点编号。为了避免重复代码,我在静态函数内部创建了一个类的实例。编译时没有任何警告(使用 -Wall)。

不幸的是,我找不到任何关于它是否是未定义行为的信息。是吗?

#include <iostream>
#include <fstream>
#include "srxDSLog.H"

extern SrxDsLog *Logger;

class Stanza {
private:
std::string config_file_path_;

public:
Stanza(std::string config_file_path) {
config_file_path_ = config_file_path;
}

std::string GetValue(std::string config_section, std::string config_setting) {
std::ifstream config_file(config_file_path_.c_str(), std::ios::in);
std::string current_section, line;
for ( ; std::getline(config_file, line); ) {
line = rtrim(line);
if (line.find(" ") == std::string::npos && line.find(":") != std::string::npos) {
current_section = line.substr(0, line.find(":"));
continue;
}
if (current_section == config_section) {
if (line.find(config_setting) != std::string::npos && line.find("=") != std::string::npos) {
return line.substr(line.find(config_setting) + config_setting.length() + 3); // we're getting the string starting after the name of the setting + " = " + 1. We're assuming there's exactly 1 space
}
}
}
if (current_section.empty()) {
Logger->WriteLog("Couldn't find section: " + config_section, LOG_ERROR, "Stanza::GetValue");
return "";
}
else {
Logger->WriteLog("Couldn't find setting: " + config_setting, LOG_ERROR, "Stanza::GetValue");
return "";
}
Logger->WriteLog("Somehow reached the end of function without returning", LOG_ERROR, "Stanza::GetValue");
return "";
}

static std::string rtrim(std::string input) {
if (input.find_last_not_of(" ") == input.length() - 1) {
return input;
}
else {
return input.substr(0, input.find_last_not_of(" ") + 1);
}
}

static int GetStoreNumber() {
Stanza store_config("/u/data/store.cfg");
std::string store_number = store_config.GetValue("store", "site");
return atoi(store_number.c_str());
}

};

最佳答案

这是完全合法且绝对安全的。

有时将 static 函数视为一个自由函数会有所帮助,它恰好在声明它的类的内部作用域。您可以声明 Stanza 类型的对象> 在自由函数中,所以在 Stanza 内的 static 成员函数中这样做很好。

T 的成员函数中定义类型为 T 的对象是有风险的情况非常少,这些情况主要是构造函数或析构函数不必担心意外递归。

关于c++ - 在同一个类的静态函数中创建一个类的实例是未定义的行为吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com