[PATCH] D112278: Support: Add Expected<T>::moveInto() to avoid extra names
    Duncan P. N. Exon Smith via Phabricator via llvm-commits 
    llvm-commits at lists.llvm.org
       
    Thu Oct 21 16:05:10 PDT 2021
    
    
  
dexonsmith created this revision.
dexonsmith added reviewers: lhames, dblaikie.
dexonsmith requested review of this revision.
Herald added a project: LLVM.
Expected<T>::moveInto() takes as an out parameter any `OtherT&` that's
assignable from `T&&`. It moves any stored value before returning
takeError().
There are two existing patterns that moveInto() cleans up:
  // If the variable is new:
  Expected<std::unique_ptr<int>> ExpectedP = makePointer();
  if (!ExpectedP)
    return ExpectedP.takeError();
  std::unique_ptr<int> P = std::move(*ExpectedP);
  
  // If the target variable already exists:
  if (Expected<T> ExpectedP = makePointer())
    P = std::move(*ExpectedP);
  else
    return ExpectedP.takeError();
moveInto() takes less typing and avoids needing to name (or leak into
the scope) an extra variable.
  // If the variable is new:
  std::unique_ptr<int> P;
  if (Error E = makePointer().moveInto(P))
    return E;
  
  // If the target variable already exists:
  if (Error E = makePointer().moveInto(P))
    return E;
Another use case is writing unit tests, to log errors (but continue)
when there's an unexpected failure. E.g.:
  // Crash on error, or undefined in non-asserts builds.
  std::unique_ptr<MemoryBuffer> MB = cantFail(makeMemoryBuffer());
  
  // Avoid crashing on error without moveInto() :(.
  Expected<std::unique_ptr<MemoryBuffer>>
      ExpectedMB = makeMemoryBuffer();
  ASSERT_THAT_ERROR(ExpectedMB.takeError(), Succeeded());
  std::unique_ptr<MemoryBuffer> MB = std::move(ExpectedMB);
  
  // Avoid crashing on error with moveInto() :).
  std::unique_ptr<MemoryBuffer> MB;
  ASSERT_THAT_ERROR(makeMemoryBuffer().moveInto(MB), Succeeded());
Repository:
  rG LLVM Github Monorepo
https://reviews.llvm.org/D112278
Files:
  llvm/docs/ProgrammersManual.rst
  llvm/include/llvm/Support/Error.h
  llvm/unittests/Support/ErrorTest.cpp
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D112278.381417.patch
Type: text/x-patch
Size: 4941 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20211021/550ca8b7/attachment.bin>
    
    
More information about the llvm-commits
mailing list