c++ const public field vs. a getter method
I want to a开发者_如何学Godd unique ID (within a single session) to each object of a certain class. One solution is to use a factory function which increments some static counter. A simpler solution is to add this counter to the class itself, e.g.:
class fooWithUniqueId {
public:
fooWithUniqueId() : id(next_id++) {...};
long id;
private:
static long next_id = 0;
}
A flaw, however, is that the id
field is public, and can be changed by the caller, thus violating its uniqueness. A traditional (well, at least in my eyes) is to make id
private, and use a getter function to access it, thus:
class fooWithUniqueId {
public:
fooWithUniqueId() : id(next_id++) {...};
long getId() const { return id; };
private:
long id;
static long next_id = 0;
}
But I'm considering a different approach. I can make id a const public class field:
class fooWithUniqueId {
public:
fooWithUniqueId() : id(next_id++) {...};
const long id;
private:
static long next_id = 0;
}
I like this way better because I don't have to keep calling getId()
each time I need the id, I can use the id as a key in a map (as copy construction correctly initializes the id of the copy object). One disadvantage I can think of is that I cannot implement assignments between fooWithUniqueId
objects, although currently I do not need this feature.
- What are the pros and cons of each approach (getter function / const field)?
- Assuming I'm using the 'const' approach, is there any way to later implement an assignment operator without breaking the code?
Thanks, Boaz
I can use the id as a key in a map (as copy construction correctly initializes the id of the copy object)
What do you mean by "correctly"? The default copy constructor will copy the ID, whether it is stored in a private or a public member variable, and you will end up with two objects sharing the same ID. This might not be what you want.
In general, you should never use public variables in C++ as it violates proper encapsulation. Always use a (inline
) getter method. The only disadvantage is that you have to type a few more characters.
I strongly suggest that you stick to best practices and use a private field with a getter function.
It is quite ok to have a public member constant in a class, if the design shows that it should never change. A unique id seems like such a case.
The fact that the const member disables assignment seems like an advantage to me. If you assign one instance to another, the ids will not be unique anymore!
精彩评论