isocpp / isocpp/CppCoreGuidelines

Why Resource-Management is no discussion about shared_ptr<widget>&& and unique_ptr<widget>&& ?

Open
#1,916 2 comments 0 reactions 1 assignee View on GitHub

@BjarneStroustrup is already working on this.

Since Jul 13, 2022.

Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

Should add the discussion about shared_ptr<widget>&& and unique_ptr<widget>&& in Smart pointer rule summary .

Link: Smart pointer rule summary

For R.34's example code, when enter the function, the shared_ptr is copy-constructed, and this requires incrementing the strong reference count. This can incur performance costs. But if the parameter type is shared_ptr<widget>&& , this directly addresses the cost. The rvalue reference type shared_ptr<widget>&& is more efficient than the value type shared_ptr<widget> . So, I don't understand R.34 Enforcement's final line:

  • (Simple) ((Foundation)) Warn if a function takes a Shared_pointer<T> by rvalue reference. Suggesting taking it by value instead.

I modified the example code for R.34 , I think the example code should be written like this:

class WidgetUser
{
public:
    // the parameter type is shared_ptr<widget>&&
    explicit WidgetUser(std::shared_ptr<widget>&& w) noexcept:
        m_widget{std::move(w)} {}
    // ...
private:
    std::shared_ptr<widget> m_widget;
};

On the other hand, R.32 and R.33 talk about unique_ptr<widget> and unique_ptr<widget>& . But I think, unique_ptr<widget>&& is also very useful. If we take a unique_ptr<widget> parameter, its total cost would be two moves. But if we take a unique_ptr<widget>&& parameter, the total cost is one move.

The screenshots from the Scott Meyers's Effective Modern C++ Item41 is as follows:
Effective Modern C++ Item41

So, I think we should add the discussion about shared_ptr<widget>&& and unique_ptr<widget>&& in Smart pointer rule summary .

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.