should I mark a method as const if it does not modify the instance of a class itself, but an external mechanism embedded in the class?

Viewed 48

I use epoll for prototyping a little TCP server, just for pedagogic purposes. epoll has a function int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);. When used with the operation (op) EPOLL_CTL_ADD, the function add the fd to the list of fd watched by epoll.

On my side, I have written a wrapper class for epoll in C++, which provides some useful functions, including Epoll::add_connection(int fd). This function call epoll_ctl() and add the fd passed as parameter in the epoll instance.

So, my question:

Epoll::add_connection(int fd) doesn't modify an instance of my class, no attributes are modified. But, since my class represent more or less epoll itself, in a way the instance is modified...

Should I mark this function const or not ?

1 Answers

General consideration: I'd rather look at what the function logically does: It does change the internal representation, even though in given case no embedded member actually is modified.

If for whatever reason need for arises later on (like additionally storing the file descriptors in a std::vector – or at least remembering the number of file descriptors stored) you'd need to change the signature – and then existing code relying on a const object would break!

Related