C 单功能变量放置

C++ single-function variable placement

本文关键字:变量 功能 单功能      更新时间:2023-10-16

我正在编写一个从文件中读取数据的类。该项目仍在开发中,很可能会以后更改文件名或路径,因此我将其存储在std ::字符串中以进行更快编辑。

鉴于文件名将在函数中多次使用,但仅在一个函数中使用,是否有关于我应该在何处定义变量的规范CPP规则?

//don't know where I'll define this
std::string file_name = "path/to/file.foo";

//a.h file
class A {
public:
  void fileFunc();
private:
  //do i define it here?
};

//a.cpp file
A::fileFunc() {
  //or do i define it here?
  std::ifstream in(file_name);
  if(in) {
    //do things
  }
  else {
    std::cerr << "couldn't open " << file_name;
  }
}

将所有信息保持在Thiers使用的附近。

它将有助于可读性和性能。请参阅:https://en.wikipedia.org/wiki/locality_of_reference

so

A::fileFunc() {
  const std::string file_name = "path/to/file.foo"; // pls use const when you can
  ...

A::fileFunc(const std::string& file_name) {
  ...

顺便说一句,我认为这应该在https://codereview.stackexchange.com/上,而不是stackoverflow。