On Thu, Apr 28, 2016 at 8:22 PM, <jww...@mozilla.com> wrote: > Jim Blandy於 2016年4月28日星期四 UTC+8下午1時51分15秒寫道: > > I don't really think it's a good example. TakeMediaIfKnown is accepting a > > UniquePtr<MediaFile> as an inout parameter: it uses, and may modify, its > > value. It should take UniquePtr<MediaFile> &. > IIUC, UniquePtr<T> can't be an inout parameter for its unique semantics > which owns sole ownership of an object. The caller won't be able to use the > object in a meaningful way after the function returns. > > > I'm not sure I understand. Maybe it would help if we had a more concrete example to talk about:
$ cat unique-inout.cc #include <stdio.h> #include "mozilla/UniquePtr.h" using mozilla::UniquePtr; struct MediaFile { const char *name; MediaFile(const char *name) : name(name) { printf("constructing %s\n", name); } ~MediaFile() { printf("destructing %s\n", name); } }; int foo(UniquePtr<MediaFile> &arg, bool pleaseSwap) { if (pleaseSwap) { UniquePtr<MediaFile> ptr = Move(arg); arg = UniquePtr<MediaFile>(new MediaFile("foo's")); } } int main(int argc, char **argv) { UniquePtr<MediaFile> first(new MediaFile("first")); printf("before first call\n"); foo(first, false); printf("after first call\n"); UniquePtr<MediaFile> second(new MediaFile("second")); printf("before second call\n"); foo(second, true); printf("after second call\n"); } $ ln -sf /home/jimb/moz/dbg/mfbt mozilla $ g++ -std=c++11 -I . unique-inout.cc -o unique-inout $ ./unique-inout constructing first before first call after first call constructing second before second call constructing foo's destructing second after second call destructing foo's destructing first $ The first MediaFile's destructor doesn't run until the end of main. The second MediaFile's destructor runs during the second call to foo, and then foo's MedialFile's destructor runs at the end of main. That's what I meant by a function taking a UniquePtr as an inout parameter. It seemed to me like the function Gerald imagined should be written as in my code above, rather than passing Move(...) as the argument. Although the language doesn't enforce it, I think Move should be reserved for unconditional transfers of ownership. _______________________________________________ dev-platform mailing list dev-platform@lists.mozilla.org https://lists.mozilla.org/listinfo/dev-platform