Is raw_ptr<> in a typedef allowed?

414 views
Skip to first unread message

Luciano Pacheco

unread,
Jul 27, 2022, 1:40:44 AM7/27/22
to memory-s...@chromium.org
Hi all,

This came up in a code review CL:3764409 (see example below).

Using raw_ptr<> in a typedef of map, this typedef is also used in an iterator inside a member function.  Is it ok to use the raw_ptr<> here?
class PendingDialog {
  using Map = std:map<SomeID, raw_ptr<DialogImpl>>;
  Map map_;

  DialogImpl* Find(SomeID id) {
    // *** Indirectly using raw_ptr<> here.
    Map::const_iterator it = map_.find(id);
    if (it == map_.end())
      return nullptr;
    return it->second;
  }
}

I'm following the guidance from //main/base/memory/raw_ptr.md.
"""
You don’t have to, but may use raw_ptr<T>, in the following scenarios:

Pointers that are used as an element type of collections/wrappers. E.g. std::vector<T*> and std::vector<raw_ptr<T>> are both okay, but prefer the latter if the collection is a class field (note that some of the perf optimizations above might still apply and argue for using a raw C++ pointer).

"""

Cheers,

Luciano Pacheco


Daniel Cheng

unread,
Jul 27, 2022, 2:19:53 AM7/27/22
to Luciano Pacheco, memory-s...@chromium.org
Yes, this particular usage is fine: an iterator really just provides a reference to an entry in the map. It's not creating a local variable with the raw_ptr<T> type, which is what's discouraged in https://chromium.googlesource.com/chromium/src/+/main/base/memory/raw_ptr.md#pointers-in-locations-other-than-fields.

There are still ways to create raw_ptr<T> locals unintentionally though, and it'd be best to avoid that where reasonable. For example:

  for (const auto [id, dialog] : map_) {
    ...
  }

which would copy `id` and `dialog` for each map entry [1], creating a raw_ptr<T> local. Instead, write:

  for (const auto& [id, dialog] : map_) {
    ...
  }

Which doesn't copy at all.
(Though it looks like clang does warn about some instances of this, which I did not know about until today!)

Daniel


--
You received this message because you are subscribed to the Google Groups "memory-safety-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to memory-safety-...@chromium.org.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/memory-safety-dev/CACqyNVAs0fxLHS39MU5ZzdDCPu4xHJJB16%2BGuEC39ho8vB89qA%40mail.gmail.com.
For more options, visit https://groups.google.com/a/chromium.org/d/optout.

Luciano Pacheco

unread,
Jul 27, 2022, 2:39:52 AM7/27/22
to Daniel Cheng, Luciano Pacheco, memory-s...@chromium.org
Thanks for the quick response. :-)
Reply all
Reply to author
Forward
0 new messages