rspec/rules/S4998/rule.adoc

47 lines
1.6 KiB
Plaintext
Raw Normal View History

If you use `+std::unique_ptr<T> const &+` for a function parameter type, it means that the function will not be able to alter the ownership of the pointed-to object by the `+unique_ptr+`:
* It cannot acquire ownership of the pointed-to object (this would require a parameter of type `+std::unique_ptr<T>+`)
* It cannot transfer the object ownership to someone else (this would require a `+std::unique_ptr<T> &+`).
That means the function can only observe the pointed-to object, and in this case passing a `+T*+` (if the `+unique_ptr+` can be null) or a `+T&+` (if it cannot) provides the same features, while also allowing the function to work with objects that are not handled by a `+unique_ptr+` (E.G. objects on the stack, in a `+vector+`, or in another kind of smart pointer), thus making the function more general-purpose.
== Noncompliant Code Example
----
using namespace std;
void draw(unique_ptr<Shape> const &shape); // Noncompliant
void drawAll(vector<unique_ptr<Shape>> v)
{
for (auto &shape : v) {
if (shape) {
draw(shape);
}
}
}
----
== Compliant Solution
----
using namespace std;
void draw(Shape const &shape); // Compliant
void drawAll(vector<unique_ptr<Shape>> v)
{
for (auto &shape : v) {
if (shape) {
draw(*shape);
}
}
}
----
== See
* https://github.com/isocpp/CppCoreGuidelines/blob/036324/CppCoreGuidelines.md#r32-take-a-unique_ptrwidget-parameter-to-express-that-a-function-assumes-ownership-of-a-widget[C++ Core Guidelines R.32] - Take a unique_ptr<widget> parameter to express that a function assumes ownership of a widget