rspec/rules/S5008/rule.adoc
Arseniy Zaostrovnykh 7ca29f686f Force linebreaks
2021-02-02 15:02:10 +01:00

52 lines
2.2 KiB
Plaintext

``++void*++`` is a pointer to memory of unknown type, and therefore works outside of the safety net provided by the type system. While it can be useful in a function body to interface with external code, there is no good reason to step out of the robust {cpp} type system when defining a function, either for the function parameters, or for the function return type. For the same reasons, having a member variable of type ``++void*++`` is not recommended.
If you want to work with raw memory buffer, use ``++unsigned char *++`` (or ``++byte *++`` if your compiler supports it).
If you want to work with different types of data, define a function template and use typed pointers, instead of ``++void *++``. If you want a single object to be able to stores objects of different types, ``++std::any++`` can also be a type-safe alternative to ``++void*++``.
If you want to provide to users of an API an opaque type, declare a type and don't provide its definition (like with ``++FILE*++``).
Note that ``++void*++`` is commonly used to communicate data of unknown type with C code. This rule will nevertheless raise an issue in this case, but it can be ignored.
== Noncompliant Code Example
----
void saveBuffer(void *buffer, size_t size); // Noncompliant
void duplicate(void* destination, size_t count, void *source, size_t size); // Noncompliant
class Process {
// ...
void *userData;
};
using UserData = void*; // Noncompliant
----
== Compliant Solution
----
void saveBuffer(unsigned char *buffer, size_t size);
template<class T>
void duplicate(T* destination, size_t count, T *source);
class Process {
// ...
std::any userData;
};
----
== Exceptions
``++void*++`` can be useful when interfacing with C. As such, the rule will ignore ``++extern "C"++`` functions, as well as types with standard layout.
== See
* https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#i4-make-interfaces-precisely-and-strongly-typed[{cpp} Core Guidelines I.4] - Make interfaces precisely and strongly typed
* https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#t3-use-templates-to-express-containers-and-ranges[{cpp} Core Guidelines T.3] - Use templates to express containers and ranges