문제

Currently I am working on an application in C++ which I want to be const correct. Meaning using const on parameters wherever possible, and stuff like that. However, this C++ application makes use of a C library which does not use const often. The problem I'm running into is when sending parameters to functions in the C library the parameters cannot be const so I am forced to do a cast.

Using const cast kind of detracts from the whole const correctness I have been working towards. When working with C libraries that are not const correct, do you just go with the flow and also not use const correctness in order to use these libraries easily? Or is there a better way that I am not seeing? Note that this is a rather small program, so isolating the part that uses the library and making just that part not const correct is not really an option.

도움이 되었습니까?

해결책

Personally, I prefer to use casts at the boundary of the library that is not const correct. The upside of this approach is that you allow your code to get the benefits of the proper usage of const. The downside is that if the library modifies an object, even "temporarily", that you've casted away const on, your program can fault.

For example, I've seen C libraries that take char * parameters that they don't logically modify. However, their parser may temporarily replace delimiters in the string with zeroes to use strcpy to extract them. If you cast away const to allow a C++ function to take a const char *, and someone passes a pointer to an object that's actually const, the "temporary" replacement of the delimiter with a zero will cause a fault.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top