0

In my .h file for my .cpp program I have the following.
FILE *sequence_file_pointer_; //holds the FILE pointer to the file itself
Then I told eclipse to generate the getters and setters and I get this interesting result.
const FILE*& getSequenceFilePointer() const;
After I thought I knew everything about pointers addresses and constants, then I see them give me this. I understand the constant on the left so that it will return a constant file pointer, but I don't understand the constant on the right and the ampersand between FILE* and the getSequenceFilePointer(). Any help?

class Configuration {
 public: 
  const FILE*& getSequenceFilePointer() const;
 private:
   FILE *sequence_file_pointer_; //holds the FILE pointer to the file itself
}
  • The const on the right makes it a `const member function`. The ampersand is called a `reference`. In this case, you could change the return type to just `FILE*` or `const FILE*` – Neil Kirk Sep 22 '14 at 19:20
  • See http://stackoverflow.com/questions/751681/meaning-of-const-last-in-a-c-method-declaration for the trailing `const`. – juanchopanza Sep 22 '14 at 19:20
  • The tool you're using for getter/setter generation is essentially boilerplate brain-dead. it simply takes the type of the member variable (`FILE*`), then generates a const-"getter" that returns a const-reference-to-type of said variable. Whether this is appropriate for your needs is up to you (I would find it highly odd if it is, as it essentially gives you a reference-to `FILE*` that you can't actually use for anything). – WhozCraig Sep 22 '14 at 19:43

1 Answers1

0

They taught me to use ampersand if I needed a reference only, not a copy, but for only classes/structures. When you say you want to return a class, an int or whatever, it is copied to the stack, and you can get it in the other function. But if you want to give it a reference only, for example you did not create the object needed to be returned within the function, you pass only 4 or 8 bytes, so you doesn't have to copy a bunch of memory.

So this is a bit weird. It seems to be a bug. The pointer is already atomic (it's unsigned long int I think). It doesn't need to pass a reference, because the reference is the same size as where it points. It's just a waste of time and memory.

radl
  • 300
  • 3
  • 12