Search code examples
c++headerconventions

C++ single-function variable placement


I'm writing a class that reads data from a file. The project is still in development, and it's likely that I'll change the file name or path later on, so I've stored it in a std::string for quicker editing.

Given that the file name is going to be used several times in a function, but is only going to be used in one function, is there a canonical cpp rule about where I should define the variable?

//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;
  }

}


Solution

  • Keeps all information close to thiers use.

    It will help the readability and the performance. See: 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
      ...
    

    or

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

    BTW, I think this should be on https://codereview.stackexchange.com/, not stackoverflow.