Difference between Arc and AtomicPtr

Yes, Cow<'a, T> has the syntax of a pointer, but it doesn't actually point: it contains a T inline.

That is, when it's Owned. If it's the Borrowed variant, then it is a pointer (of the "reference" variety), which is of course the whole point (no pun intended).

(And when T is non-Clone, such as str, Cow<T> might not ever contain a T at all because of how Owned is defined. Cow<'a, str> contains either Borrowed(&'a str) or Owned(String), both of which are pointers to str, and the Cow itself also dereferences to str.)

Put another way, there are three elements people usually talk about when it comes to smart pointers:

  1. Does it have the syntax of a pointer? (In C++, does it implement operator*? In Rust, does it implement Deref?)
  2. Is it semantically a pointer, i.e. does it refer to something that is stored not in the object itself but at some other location? This is what I mean by "indirection".
  3. Does it have some additional behavior that "raw" pointers don't have, which makes it "smart"? Usually this means having drop glue.

The easy cases are the ones that meet all three criteria. String is a smart pointer to str: you can dereference it with * and . to get a str, the data is not stored inline but in an allocation (the "pointer" part), and when you drop a non-empty String it deallocates the backing buffer (the "smart" part).

Cow<'_, T> is a little weird because of point 2: sometimes it contains an indirection, sometimes it contains a T directly. Does that make it sometimes a smart pointer? :man_shrugging:

&T and &mut T are a little weird because of point 3: depending on how you define "behavior" you might consider references to be smarter than raw pointers, or just dumb pointers with extra compile time rules. :man_shrugging:

When people say to not implement Deref for things that aren't smart pointers they're usually talking about the semantics of pointers. Obviously, anything that is Deref is syntactically a pointer by definition. But if there's no indirection, that might confuse your intuition about how the type works.

1 Like