[clang-tools-extra] [clang-tidy] Add performance-inefficient-container-assignment check (PR #222159)

Andrew Gaul via cfe-commits cfe-commits at lists.llvm.org
Tue Sep 8 14:47:34 PDT 2026


https://github.com/gaul created https://github.com/llvm/llvm-project/pull/222159

Finds assignments of a freshly constructed temporary container to a container of the same type, such as `v = std::vector<int>(n, 0);`, and rewrites them to the `assign` member function or an equivalent in-place form that reuses the destination's storage. The temporary allocates its own buffer and the move assignment then discards the one the destination already owns; `assign` writes into the existing buffer and only allocates when the new contents do not fit.

Every rewrite leaves the destination with exactly the elements the assignment would have produced:

```
  v = std::vector<int>(n, 0);          ->  v.assign(n, 0);
  v = std::vector<int>(first, last);   ->  v.assign(first, last);
  v = {first, last};                   ->  v.assign(first, last);
  v = std::vector<int>{1, 2, 3};       ->  v = {1, 2, 3};
  v = std::vector<int>(n);             ->  v.clear(); v.resize(n);
  v = std::vector<int>(other);         ->  v = other;
  s = std::string(p, n);               ->  s.assign(p, n);
  v = std::vector<int>(std::from_range, r);  ->  v.assign_range(r);  (C++23)
```
The multi-argument constructors of the standard sequence containers all have `assign` overloads with the same parameters, so their arguments pass through verbatim. `v = Container()` is not diagnosed because it releases the storage, which `clear()` would keep, and neither is `v = Container(v)`, the idiom for trimming capacity, nor a constructor call with an explicit allocator or a single argument of another type, which is a conversion rather than a copy. The warning is emitted without a fix-it when an argument refers to the destination, when the value of the assignment is used (`assign` returns void), or inside macro expansions; the two-statement `clear(); resize(n);` form is additionally limited to statements of their own whose destination and count have no side effects.

The containers are configurable through the `ContainerClasses` option, which defaults to `std::vector`, `std::deque`, `std::list`, `std::forward_list` and `std::basic_string`; `llvm::SmallVector` follows the same conventions and can be added.

Running the check over the 6,528 llvm, clang and clang-tools-extra translation units of a default build, with `llvm::SmallVector` added to `ContainerClasses`, reports 33 sites and offers a fix-it at 32 of them; the remaining one passes an iterator into the destination. Applying all 32 fix-its and rebuilding the affected translation units compiles cleanly. Typical hits are per-function resets of analysis state such as `TopDownIndex2SU = std::vector<int>(Topo.begin(), Topo.end());` in the AMDGPU scheduler, `Nodes = std::vector<Node>(NodeCount);` in SampleProfileInference, and `Sorted = {Unique.begin(), Unique.end()};` in clangd.

>From ef3a9698197c363e05602276472aaadf66c1141c Mon Sep 17 00:00:00 2001
From: Andrew Gaul <andrew at gaul.org>
Date: Tue, 8 Sep 2026 11:05:33 -0700
Subject: [PATCH] [clang-tidy] Add performance-inefficient-container-assignment
 check

Finds assignments of a freshly constructed temporary container to a
container of the same type, such as `v = std::vector<int>(n, 0);`, and
rewrites them to the `assign` member function or an equivalent in-place
form that reuses the destination's storage. The temporary allocates its
own buffer and the move assignment then discards the one the destination
already owns; `assign` writes into the existing buffer and only allocates
when the new contents do not fit.

Every rewrite leaves the destination with exactly the elements the
assignment would have produced:

  v = std::vector<int>(n, 0);          ->  v.assign(n, 0);
  v = std::vector<int>(first, last);   ->  v.assign(first, last);
  v = {first, last};                   ->  v.assign(first, last);
  v = std::vector<int>{1, 2, 3};       ->  v = {1, 2, 3};
  v = std::vector<int>(n);             ->  v.clear(); v.resize(n);
  v = std::vector<int>(other);         ->  v = other;
  s = std::string(p, n);               ->  s.assign(p, n);
  v = std::vector<int>(std::from_range, r);  ->  v.assign_range(r);  (C++23)

The multi-argument constructors of the standard sequence containers all
have `assign` overloads with the same parameters, so their arguments pass
through verbatim. `v = Container()` is not diagnosed because it releases
the storage, which `clear()` would keep, and neither is `v = Container(v)`,
the idiom for trimming capacity, nor a constructor call with an explicit
allocator or a single argument of another type, which is a conversion
rather than a copy. The warning is emitted without a fix-it when an
argument refers to the destination, when the value of the assignment is
used (`assign` returns void), or inside macro expansions; the two-statement
`clear(); resize(n);` form is additionally limited to statements of their
own whose destination and count have no side effects.

The containers are configurable through the `ContainerClasses` option,
which defaults to `std::vector`, `std::deque`, `std::list`,
`std::forward_list` and `std::basic_string`; `llvm::SmallVector` follows
the same conventions and can be added.

Running the check over the 6,528 llvm, clang and clang-tools-extra
translation units of a default build, with `llvm::SmallVector` added to
`ContainerClasses`, reports 33 sites and offers a fix-it at 32 of them;
the remaining one passes an iterator into the destination. Applying all
32 fix-its and rebuilding the affected translation units compiles cleanly.
Typical hits are per-function resets of analysis state such as
`TopDownIndex2SU = std::vector<int>(Topo.begin(), Topo.end());` in the
AMDGPU scheduler, `Nodes = std::vector<Node>(NodeCount);` in
SampleProfileInference, and `Sorted = {Unique.begin(), Unique.end()};`
in clangd.

Co-Authored-By: Claude Fable 5.1 <noreply at anthropic.com>
Claude-Session: https://claude.ai/code/session_01RN4gpjgX8QWXRuQoBzYace
---
 .../clang-tidy/performance/CMakeLists.txt     |   1 +
 .../InefficientContainerAssignmentCheck.cpp   | 320 ++++++++++++++++++
 .../InefficientContainerAssignmentCheck.h     |  40 +++
 .../performance/PerformanceTidyModule.cpp     |   3 +
 clang-tools-extra/docs/ReleaseNotes.md        |   7 +
 .../docs/clang-tidy/checks/list.md            |   1 +
 .../inefficient-container-assignment.md       |  89 +++++
 .../checkers/Inputs/Headers/std/deque         |   2 +
 .../checkers/Inputs/Headers/std/forward_list  |   2 +
 .../checkers/Inputs/Headers/std/list          |   2 +
 .../checkers/Inputs/Headers/std/string        |   3 +
 .../checkers/Inputs/Headers/std/vector        |  20 ++
 ...inefficient-container-assignment-cxx23.cpp |  15 +
 .../inefficient-container-assignment.cpp      | 245 ++++++++++++++
 14 files changed, 750 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.h
 create mode 100644 clang-tools-extra/docs/clang-tidy/checks/performance/inefficient-container-assignment.md
 create mode 100644 clang-tools-extra/test/clang-tidy/checkers/performance/inefficient-container-assignment-cxx23.cpp
 create mode 100644 clang-tools-extra/test/clang-tidy/checkers/performance/inefficient-container-assignment.cpp

diff --git a/clang-tools-extra/clang-tidy/performance/CMakeLists.txt b/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
index f55a6cf2800f3..31e88acd6c01e 100644
--- a/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
@@ -10,6 +10,7 @@ add_clang_library(clangTidyPerformanceModule STATIC
   ForRangeCopyCheck.cpp
   ImplicitConversionInLoopCheck.cpp
   InefficientAlgorithmCheck.cpp
+  InefficientContainerAssignmentCheck.cpp
   InefficientStringConcatenationCheck.cpp
   InefficientVectorOperationCheck.cpp
   MoveConstArgCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.cpp b/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.cpp
new file mode 100644
index 0000000000000..ea05e1484a9fe
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.cpp
@@ -0,0 +1,320 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "InefficientContainerAssignmentCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringExtras.h"
+#include <optional>
+#include <string>
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::performance {
+
+namespace {
+
+/// How the assignment can be rewritten without the temporary. The order
+/// matches the %select in the diagnostic.
+enum class Rewrite {
+  Assign,      ///< lhs.assign(args...)
+  AssignRange, ///< lhs.assign_range(range)
+  ClearResize, ///< lhs.clear(); lhs.resize(count)
+  InitList,    ///< lhs = {...}
+  Direct,      ///< lhs = source
+};
+
+} // namespace
+
+/// Collects the variables and members named by \p E so that arguments
+/// referring back to the destination can be detected.
+static void
+collectReferencedDecls(const Expr &E, ASTContext &Ctx,
+                       llvm::SmallPtrSetImpl<const ValueDecl *> &Decls) {
+  for (const BoundNodes &N : match(findAll(declRefExpr().bind("ref")), E, Ctx))
+    Decls.insert(N.getNodeAs<DeclRefExpr>("ref")->getDecl());
+  for (const BoundNodes &N :
+       match(findAll(memberExpr().bind("member")), E, Ctx))
+    Decls.insert(N.getNodeAs<MemberExpr>("member")->getMemberDecl());
+}
+
+static bool
+refersToAnyOf(const Expr &E, ASTContext &Ctx,
+              const llvm::SmallPtrSetImpl<const ValueDecl *> &Decls) {
+  llvm::SmallPtrSet<const ValueDecl *, 8> Referenced;
+  collectReferencedDecls(E, Ctx, Referenced);
+  return llvm::any_of(
+      Referenced, [&Decls](const ValueDecl *D) { return Decls.contains(D); });
+}
+
+/// Returns true if one of the first \p NumArgs parameters of \p Ctor has the
+/// type of a template argument of the container other than its element type.
+/// That is what the allocator parameter of the standard containers looks
+/// like, and an explicitly passed allocator has no counterpart in 'assign'.
+static bool passesAllocator(const CXXConstructorDecl &Ctor, unsigned NumArgs,
+                            const ASTContext &Ctx) {
+  const auto *Spec =
+      dyn_cast<ClassTemplateSpecializationDecl>(Ctor.getParent());
+  if (!Spec)
+    return false;
+  const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
+  for (unsigned I = 0, E = std::min(NumArgs, Ctor.getNumParams()); I < E; ++I) {
+    const QualType ParamType =
+        Ctor.getParamDecl(I)->getType().getNonReferenceType();
+    if (!ParamType->isRecordType())
+      continue;
+    for (unsigned J = 1; J < TemplateArgs.size(); ++J) {
+      const TemplateArgument &Arg = TemplateArgs[J];
+      if (Arg.getKind() == TemplateArgument::Type &&
+          ASTContext::hasSameUnqualifiedType(Arg.getAsType(), ParamType))
+        return true;
+    }
+  }
+  return false;
+}
+
+static bool isFromRangeTag(QualType T) {
+  const CXXRecordDecl *RD = T.getNonReferenceType()->getAsCXXRecordDecl();
+  return RD && RD->isInStdNamespace() && RD->getName() == "from_range_t";
+}
+
+/// A postfix expression can take a member access directly; anything else has
+/// to be parenthesized first.
+static bool needsParens(const Expr &E) {
+  const Expr *Inner = E.IgnoreImpCasts();
+  if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Inner))
+    return Call->getOperator() != OO_Subscript &&
+           Call->getOperator() != OO_Call;
+  return !isa<DeclRefExpr, MemberExpr, ArraySubscriptExpr, CallExpr, ParenExpr>(
+      Inner);
+}
+
+/// Returns the statement that directly contains \p E, looking through the
+/// implicit cleanup wrapper and parentheses, or nullptr if \p E is a
+/// subexpression or an initializer.
+static const Stmt *getEnclosingStatement(const Expr &E, ASTContext &Ctx) {
+  DynTypedNodeList Parents = Ctx.getParents(E);
+  while (Parents.size() == 1) {
+    const auto *S = Parents[0].get<Stmt>();
+    if (!S)
+      return nullptr;
+    if (!isa<ExprWithCleanups, ParenExpr>(S))
+      return S;
+    Parents = Ctx.getParents(*S);
+  }
+  return nullptr;
+}
+
+InefficientContainerAssignmentCheck::InefficientContainerAssignmentCheck(
+    StringRef Name, ClangTidyContext *Context)
+    : ClangTidyCheck(Name, Context),
+      ContainerClasses(utils::options::parseStringList(Options.get(
+          "ContainerClasses", "::std::vector;::std::deque;::std::list;"
+                              "::std::forward_list;::std::basic_string"))) {}
+
+void InefficientContainerAssignmentCheck::storeOptions(
+    ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "ContainerClasses",
+                utils::options::serializeStringList(ContainerClasses));
+}
+
+void InefficientContainerAssignmentCheck::registerMatchers(
+    MatchFinder *Finder) {
+  if (ContainerClasses.empty())
+    return;
+
+  const auto Container = cxxRecordDecl(hasAnyName(ContainerClasses));
+  const auto Temporary =
+      cxxConstructExpr(hasDeclaration(cxxConstructorDecl(ofClass(Container))))
+          .bind("ctor");
+
+  // Match: lhs = Container(...) and lhs = Container{...}, where the assignment
+  // is the container's own 'operator='. Template instantiations are skipped:
+  // the rewrite might not fit every instantiation, and the temporary is only
+  // visible where the types are known.
+  Finder->addMatcher(
+      cxxOperatorCallExpr(
+          unless(isInTemplateInstantiation()), hasOverloadedOperatorName("="),
+          callee(cxxMethodDecl(ofClass(Container))),
+          hasArgument(0, expr().bind("lhs")),
+          hasArgument(1, ignoringImplicit(anyOf(
+                             Temporary, cxxFunctionalCastExpr(has(
+                                            ignoringImplicit(Temporary)))))))
+          .bind("op"),
+      this);
+}
+
+void InefficientContainerAssignmentCheck::check(
+    const MatchFinder::MatchResult &Result) {
+  const auto *Op = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("op");
+  const auto *LHS = Result.Nodes.getNodeAs<Expr>("lhs");
+  const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructExpr>("ctor");
+  ASTContext &Ctx = *Result.Context;
+
+  // The rewrites call members of the destination, so the temporary must have
+  // exactly the destination's type; a derived class or another specialization
+  // would go through a different 'operator='.
+  if (!ASTContext::hasSameUnqualifiedType(LHS->getType(), Ctor->getType()))
+    return;
+
+  const CXXConstructorDecl *CtorDecl = Ctor->getConstructor();
+  SmallVector<const Expr *, 4> Args;
+  for (const Expr *Arg : Ctor->arguments())
+    if (!isa<CXXDefaultArgExpr>(Arg))
+      Args.push_back(Arg);
+
+  // 'lhs = Container();' releases the storage rather than reusing it, which is
+  // usually the point; 'clear()' would keep the capacity.
+  if (Args.empty())
+    return;
+
+  // 'assign' has no allocator parameter.
+  if (Args.size() >= 2 && passesAllocator(*CtorDecl, Args.size(), Ctx))
+    return;
+
+  Rewrite Form = Rewrite::Assign;
+  const InitListExpr *InitList = nullptr;
+  if (const auto *StdInitList =
+          dyn_cast<CXXStdInitializerListExpr>(Args[0]->IgnoreParenImpCasts());
+      StdInitList && Args.size() == 1) {
+    Form = Rewrite::InitList;
+    InitList =
+        dyn_cast<InitListExpr>(StdInitList->getSubExpr()->IgnoreImplicit());
+  } else if (Args.size() == 1) {
+    if (CtorDecl->isCopyOrMoveConstructor()) {
+      if (!ASTContext::hasSameUnqualifiedType(Args[0]->getType(),
+                                              LHS->getType()))
+        return;
+      Form = Rewrite::Direct;
+    } else if (CtorDecl->getParamDecl(0)
+                   ->getType()
+                   .getNonReferenceType()
+                   ->isIntegralOrEnumerationType()) {
+      Form = Rewrite::ClearResize;
+    } else {
+      // A conversion from another type: the temporary is the conversion
+      // itself, and removing it is a different transformation.
+      return;
+    }
+  } else if (isFromRangeTag(CtorDecl->getParamDecl(0)->getType())) {
+    if (Args.size() != 2)
+      return;
+    Form = Rewrite::AssignRange;
+  }
+
+  llvm::SmallPtrSet<const ValueDecl *, 4> LHSDecls;
+  collectReferencedDecls(*LHS, Ctx, LHSDecls);
+  const auto MentionsDestination = [&](const Expr *Arg) {
+    return refersToAnyOf(*Arg, Ctx, LHSDecls);
+  };
+
+  // 'x = Container(x);' copies a container into itself to trim its capacity;
+  // that temporary is the point rather than waste.
+  if (Form == Rewrite::Direct && MentionsDestination(Args[0]))
+    return;
+
+  // 'assign' must not be given iterators, pointers or elements that refer into
+  // the container it replaces. Counts and other arithmetic values are computed
+  // before the call and are harmless.
+  const bool AliasesDestination = llvm::any_of(Args, [&](const Expr *Arg) {
+    return !Arg->getType()->isArithmeticType() && MentionsDestination(Arg);
+  });
+
+  // 'assign', 'clear' and 'resize' do not yield the container, so those
+  // rewrites need the value of the assignment to be discarded.
+  const Stmt *Parent = getEnclosingStatement(*Op, Ctx);
+  const bool ValueDiscarded =
+      isa_and_nonnull<CompoundStmt, IfStmt, WhileStmt, DoStmt, ForStmt,
+                      CXXForRangeStmt, CaseStmt, DefaultStmt, LabelStmt,
+                      AttributedStmt>(Parent);
+  const bool OwnStatement = isa_and_nonnull<CompoundStmt>(Parent);
+
+  std::optional<std::string> Replacement;
+  if (!Op->getBeginLoc().isMacroID() && !Op->getEndLoc().isMacroID()) {
+    bool Rewritable = true;
+    switch (Form) {
+    case Rewrite::Assign:
+    case Rewrite::AssignRange:
+      Rewritable = ValueDiscarded && !AliasesDestination;
+      break;
+    case Rewrite::ClearResize:
+      // Two statements, in which the destination is named twice and the
+      // count is evaluated after 'clear()'.
+      Rewritable = OwnStatement && !LHS->HasSideEffects(Ctx) &&
+                   !Args[0]->HasSideEffects(Ctx) &&
+                   !MentionsDestination(Args[0]);
+      break;
+    case Rewrite::InitList:
+      // The initializer list is materialized before the assignment.
+      Rewritable = InitList != nullptr;
+      break;
+    case Rewrite::Direct:
+      break;
+    }
+
+    if (Rewritable) {
+      const auto GetText = [&](SourceRange R) {
+        return Lexer::getSourceText(CharSourceRange::getTokenRange(R),
+                                    *Result.SourceManager, getLangOpts());
+      };
+      const StringRef LHSText = GetText(LHS->getSourceRange());
+      bool Valid = !LHSText.empty();
+      SmallVector<StringRef, 4> ArgTexts;
+      for (const Expr *Arg : Args) {
+        ArgTexts.push_back(GetText(Arg->getSourceRange()));
+        Valid = Valid && !ArgTexts.back().empty();
+      }
+      const std::string Dest =
+          needsParens(*LHS) ? ("(" + LHSText + ")").str() : LHSText.str();
+      if (Valid) {
+        switch (Form) {
+        case Rewrite::Assign:
+          Replacement = Dest + ".assign(" + llvm::join(ArgTexts, ", ") + ")";
+          break;
+        case Rewrite::AssignRange:
+          Replacement = Dest + ".assign_range(" + ArgTexts[1].str() + ")";
+          break;
+        case Rewrite::ClearResize:
+          Replacement =
+              Dest + ".clear(); " + Dest + ".resize(" + ArgTexts[0].str() + ")";
+          break;
+        case Rewrite::InitList: {
+          const StringRef ListText = GetText(InitList->getSourceRange());
+          if (!ListText.empty())
+            Replacement = (LHSText + " = " + ListText).str();
+          break;
+        }
+        case Rewrite::Direct:
+          Replacement = (LHSText + " = " + ArgTexts[0]).str();
+          break;
+        }
+      }
+    }
+  }
+
+  const auto Diag =
+      diag(Op->getOperatorLoc(),
+           "inefficient assignment from a temporary '%0'; "
+           "%select{use 'assign'|use 'assign_range'|use 'clear' and 'resize'|"
+           "assign the initializer list directly|assign the source directly}1 "
+           "to reuse the existing storage")
+      << CtorDecl->getParent()->getQualifiedNameAsString()
+      << static_cast<int>(Form);
+  if (Replacement)
+    Diag << FixItHint::CreateReplacement(Op->getSourceRange(), *Replacement);
+}
+
+} // namespace clang::tidy::performance
diff --git a/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.h b/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.h
new file mode 100644
index 0000000000000..7468b683f4cfe
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.h
@@ -0,0 +1,40 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_INEFFICIENTCONTAINERASSIGNMENTCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_INEFFICIENTCONTAINERASSIGNMENTCHECK_H
+
+#include "../ClangTidyCheck.h"
+#include <vector>
+
+namespace clang::tidy::performance {
+
+/// Finds assignments of a freshly constructed temporary container to a
+/// container of the same type and suggests the `assign` member function, or
+/// an equivalent in-place rewrite, that reuses the existing storage.
+///
+/// For the user-facing documentation see:
+/// https://clang.llvm.org/extra/clang-tidy/checks/performance/inefficient-container-assignment.html
+class InefficientContainerAssignmentCheck : public ClangTidyCheck {
+public:
+  InefficientContainerAssignmentCheck(StringRef Name,
+                                      ClangTidyContext *Context);
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+    return LangOpts.CPlusPlus;
+  }
+
+private:
+  const std::vector<StringRef> ContainerClasses;
+};
+
+} // namespace clang::tidy::performance
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_INEFFICIENTCONTAINERASSIGNMENTCHECK_H
diff --git a/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp b/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
index 9eee02494be91..6115b9aad0f51 100644
--- a/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
@@ -14,6 +14,7 @@
 #include "ForRangeCopyCheck.h"
 #include "ImplicitConversionInLoopCheck.h"
 #include "InefficientAlgorithmCheck.h"
+#include "InefficientContainerAssignmentCheck.h"
 #include "InefficientStringConcatenationCheck.h"
 #include "InefficientVectorOperationCheck.h"
 #include "MoveConstArgCheck.h"
@@ -50,6 +51,8 @@ class PerformanceModule : public ClangTidyModule {
         "performance-implicit-conversion-in-loop");
     CheckFactories.registerCheck<InefficientAlgorithmCheck>(
         "performance-inefficient-algorithm");
+    CheckFactories.registerCheck<InefficientContainerAssignmentCheck>(
+        "performance-inefficient-container-assignment");
     CheckFactories.registerCheck<InefficientStringConcatenationCheck>(
         "performance-inefficient-string-concatenation");
     CheckFactories.registerCheck<InefficientVectorOperationCheck>(
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index 6fe497e5f6eaf..50987c3464c1c 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -113,6 +113,13 @@ infrastructure are described first, followed by tool-specific sections.
   Finds calls to `value_or` (and alternative spellings `valueOr`,
   `ValueOr`) on optional types where the return type is expensive to copy.
 
+- New {doc}`performance-inefficient-container-assignment
+  <clang-tidy/checks/performance/inefficient-container-assignment>` check.
+
+  Finds assignments of a freshly constructed temporary container to a container
+  of the same type, such as `v = std::vector<int>(n, 0);`, and suggests
+  `assign` or an equivalent in-place rewrite that reuses the existing storage.
+
 - New {doc}`portability-avoid-pragma-comment
   <clang-tidy/checks/portability/avoid-pragma-comment>` check.
 
diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.md b/clang-tools-extra/docs/clang-tidy/checks/list.md
index 5a220b13eb599..fa653744676ea 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.md
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.md
@@ -357,6 +357,7 @@ readability/*
 | {doc}`performance-for-range-copy <performance/for-range-copy>` | Yes |
 | {doc}`performance-implicit-conversion-in-loop <performance/implicit-conversion-in-loop>` |  |
 | {doc}`performance-inefficient-algorithm <performance/inefficient-algorithm>` | Yes |
+| {doc}`performance-inefficient-container-assignment <performance/inefficient-container-assignment>` | Yes |
 | {doc}`performance-inefficient-string-concatenation <performance/inefficient-string-concatenation>` |  |
 | {doc}`performance-inefficient-vector-operation <performance/inefficient-vector-operation>` | Yes |
 | {doc}`performance-move-const-arg <performance/move-const-arg>` | Yes |
diff --git a/clang-tools-extra/docs/clang-tidy/checks/performance/inefficient-container-assignment.md b/clang-tools-extra/docs/clang-tidy/checks/performance/inefficient-container-assignment.md
new file mode 100644
index 0000000000000..81e92efedadfe
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/performance/inefficient-container-assignment.md
@@ -0,0 +1,89 @@
+```{title} clang-tidy - performance-inefficient-container-assignment
+```
+
+# performance-inefficient-container-assignment
+
+Finds assignments of a freshly constructed temporary container to a container
+of the same type, such as `v = std::vector<int>(n, 0);`, and suggests the
+`assign` member function or an equivalent in-place rewrite. The temporary
+allocates its own buffer, and the move assignment then discards the buffer the
+destination already owns. `assign` writes into the existing buffer and only
+allocates when the new contents do not fit.
+
+```cpp
+std::vector<int> v;
+std::string s;
+
+v = std::vector<int>(n, 0);           // fix-it: v.assign(n, 0);
+v = std::vector<int>(first, last);    // fix-it: v.assign(first, last);
+v = std::vector<int>{1, 2, 3};        // fix-it: v = {1, 2, 3};
+v = std::vector<int>(n);              // fix-it: v.clear(); v.resize(n);
+v = std::vector<int>(other);          // fix-it: v = other;
+s = std::string(n, ' ');              // fix-it: s.assign(n, ' ');
+s = std::string(str, pos, count);     // fix-it: s.assign(str, pos, count);
+```
+
+A braced list that does not fit the element type, such as
+`v = {first, last};`, list-initializes the same kind of temporary through a
+multi-argument constructor and is diagnosed as well.
+
+Every rewrite leaves the destination with exactly the elements the assignment
+would have produced:
+
+- The arguments of a constructor taking two or more arguments are passed to
+  `assign` unchanged. Every such constructor of a standard sequence container
+  has an `assign` overload with the same parameters. In C++23,
+  `Container(std::from_range, r)` becomes `assign_range(r)`.
+- An initializer list is assigned directly; `operator=(std::initializer_list)`
+  is specified to behave like `assign`.
+- A single element count, `Container(n)`, becomes `clear()` followed by
+  `resize(n)`, which value-initializes the elements in place. This takes two
+  statements, so it is only rewritten when the assignment is a statement of
+  its own inside a block, the destination has no side effects, and the count
+  neither has side effects nor mentions the destination, because the count
+  is evaluated after `clear()`.
+- A copy or move of another container of the same type, `Container(other)`,
+  becomes `= other`.
+
+The rewrites work in place. If copying an element throws partway through, the
+destination is left in a valid but unspecified state, whereas the original
+assignment would have left it unchanged. For trivially copyable elements, the
+common case, there is no difference.
+
+The following are not diagnosed:
+
+- `v = Container();` and `v = Container{};` release the storage of `v`;
+  `clear()` would keep the capacity, which is a different behavior.
+- `v = std::vector<int>(v);`, the idiom for trimming the capacity of `v` to
+  its size; there the temporary is the point.
+- Constructors with an explicitly passed allocator; `assign` has no allocator
+  parameter.
+- A single argument of another type, such as `std::string(ptr)`; the temporary
+  is the conversion itself, not a copy that `assign` could avoid.
+- Initializations such as `std::vector<int> v = std::vector<int>(n, 0);`;
+  guaranteed copy elision already makes them cheap.
+
+The warning is emitted without a fix-it when an iterator, pointer or element
+argument refers to the destination, for example
+`v = std::vector<int>(v.begin() + 1, v.end());`, because `assign` must not be
+given iterators into the container it replaces (an `erase` is the right
+rewrite for that example; a count such as `v.size()` is computed before
+`assign` runs and is fine); when the value of the assignment is used, because
+`assign`, `clear` and `resize` do not yield the container; and inside macro
+expansions. The check cannot see through pointers or iterators that are stored
+in other variables, so the fix-it assumes such arguments do not refer into the
+destination.
+
+## Options
+
+```{option} ContainerClasses
+
+Semicolon-separated list of fully qualified names of container classes to
+consider. Default is `::std::vector;::std::deque;::std::list;::std::forward_list;::std::basic_string`.
+The classes must follow the conventions of the standard sequence containers:
+every constructor taking two or more arguments, other than a trailing
+allocator, has an `assign` overload with the same parameters; a single
+integral constructor argument is an element count for `resize`; and
+`operator=` accepts an initializer list. `::llvm::SmallVector` is an example
+of a compatible class.
+```
diff --git a/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/deque b/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/deque
index 9f7393b467321..b31b3ed72debd 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/deque
+++ b/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/deque
@@ -35,6 +35,8 @@ public:
 
   deque() = default;
   deque(initializer_list<T>) {}
+  explicit deque(size_t count);
+  deque(size_t count, const T &value);
 
   iterator begin();
   const_iterator begin() const;
diff --git a/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/forward_list b/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/forward_list
index b2a6521c0d331..98458fd1af1b1 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/forward_list
+++ b/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/forward_list
@@ -34,6 +34,8 @@ public:
 
   forward_list() = default;
   forward_list(initializer_list<T>) {}
+  explicit forward_list(size_t count);
+  forward_list(size_t count, const T &value);
 
   iterator begin();
   const_iterator begin() const;
diff --git a/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/list b/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/list
index a5ea99180869a..0a71eeb3de34e 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/list
+++ b/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/list
@@ -35,6 +35,8 @@ public:
 
   list() = default;
   list(initializer_list<T>) {}
+  explicit list(size_t count);
+  list(size_t count, const T &value);
 
   iterator begin();
   const_iterator begin() const;
diff --git a/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/string b/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/string
index 766f240c655fb..7e0d62a8d9df0 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/string
+++ b/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/string
@@ -28,6 +28,7 @@ struct basic_string {
   basic_string(const C *p, size_type count);
   basic_string(const C *b, const C *e);
   basic_string(size_t, C);
+  basic_string(const basic_string &str, size_type pos, size_type n = npos);
   operator basic_string_view<C, T>() const;
 
   ~basic_string();
@@ -44,6 +45,8 @@ struct basic_string {
   _Type& append(const C *s, size_type n);
   _Type& assign(const C *s);
   _Type& assign(const C *s, size_type n);
+  _Type& assign(size_type count, C ch);
+  _Type& assign(const basic_string &str, size_type pos, size_type n = npos);
 
   int compare(const _Type&) const;
   int compare(const C* s) const;
diff --git a/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/vector b/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/vector
index e7d85f9ecce91..2f576f348a142 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/vector
+++ b/clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/vector
@@ -6,6 +6,13 @@
 
 namespace std {
 
+#if __cplusplus >= 202302L
+struct from_range_t {
+  explicit from_range_t() = default;
+};
+inline constexpr from_range_t from_range{};
+#endif
+
 template <typename T, typename A = allocator<T>>
 class vector {
 public:
@@ -19,7 +26,13 @@ public:
   vector();
   vector(size_type count);
   vector(size_type count, const T &value, const A &alloc = A());
+  template <typename InputIt, typename = decltype(*InputIt())>
+  vector(InputIt first, InputIt last, const A &alloc = A());
   vector(initializer_list<T>, const A &alloc = A());
+#if __cplusplus >= 202302L
+  template <typename R>
+  vector(from_range_t, R &&range, const A &alloc = A());
+#endif
   vector(const vector &other);
   vector(vector &&other);
   ~vector();
@@ -68,6 +81,13 @@ public:
   void resize(size_type count, const T &value);
 
   void assign(size_type count, const T &value);
+  template <typename InputIt, typename = decltype(*InputIt())>
+  void assign(InputIt first, InputIt last);
+  void assign(initializer_list<T>);
+#if __cplusplus >= 202302L
+  template <typename R>
+  void assign_range(R &&range);
+#endif
 
   iterator insert(const_iterator pos, const T &value);
   iterator insert(const_iterator pos, T &&value);
diff --git a/clang-tools-extra/test/clang-tidy/checkers/performance/inefficient-container-assignment-cxx23.cpp b/clang-tools-extra/test/clang-tidy/checkers/performance/inefficient-container-assignment-cxx23.cpp
new file mode 100644
index 0000000000000..ca9ad69b594c2
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/performance/inefficient-container-assignment-cxx23.cpp
@@ -0,0 +1,15 @@
+// RUN: %check_clang_tidy -std=c++23-or-later %s performance-inefficient-container-assignment %t
+
+#include <vector>
+
+void fromRange(std::vector<int> &V, const std::vector<int> &Other) {
+  V = std::vector<int>(std::from_range, Other);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; use 'assign_range' to reuse the existing storage [performance-inefficient-container-assignment]
+  // CHECK-FIXES: V.assign_range(Other);
+}
+
+void fromRangeWithAllocator(std::vector<int> &V, const std::vector<int> &Other,
+                            std::allocator<int> Alloc) {
+  // An explicitly passed allocator has no counterpart in 'assign_range'.
+  V = std::vector<int>(std::from_range, Other, Alloc);
+}
diff --git a/clang-tools-extra/test/clang-tidy/checkers/performance/inefficient-container-assignment.cpp b/clang-tools-extra/test/clang-tidy/checkers/performance/inefficient-container-assignment.cpp
new file mode 100644
index 0000000000000..a5e283d828542
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/performance/inefficient-container-assignment.cpp
@@ -0,0 +1,245 @@
+// RUN: %check_clang_tidy %s performance-inefficient-container-assignment %t
+
+#include <deque>
+#include <forward_list>
+#include <list>
+#include <string>
+#include <utility>
+#include <vector>
+
+using size_type = std::vector<int>::size_type;
+
+std::vector<int> &getVector();
+size_type getCount();
+
+struct Holder {
+  std::vector<int> Items;
+  std::vector<int> *Ptr;
+  size_type Count;
+};
+
+void fill(std::vector<int> &V, size_type N) {
+  V = std::vector<int>(N, 0);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; use 'assign' to reuse the existing storage [performance-inefficient-container-assignment]
+  // CHECK-FIXES: V.assign(N, 0);
+
+  // Expression arguments pass through verbatim.
+  V = std::vector<int>(N + 1, -1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: V.assign(N + 1, -1);
+}
+
+void range(std::vector<int> &V, const int *Begin, const int *End,
+           const std::vector<int> &Other) {
+  V = std::vector<int>(Begin, End);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: V.assign(Begin, End);
+
+  V = std::vector<int>(Other.begin(), Other.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: V.assign(Other.begin(), Other.end());
+}
+
+void bracedRange(std::vector<int> &V, const int *Begin, const int *End,
+                 std::string &S, const char *Chars, size_type N) {
+  // A braced list that does not fit the element type list-initializes the
+  // same kind of temporary through a multi-argument constructor.
+  V = {Begin, End};
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: V.assign(Begin, End);
+
+  S = {Chars, N};
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::basic_string'; use 'assign'
+  // CHECK-FIXES: S.assign(Chars, N);
+}
+
+void initializerList(std::vector<int> &V) {
+  V = std::vector<int>{1, 2, 3};
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; assign the initializer list directly to reuse the existing storage
+  // CHECK-FIXES: V = {1, 2, 3};
+
+  V = std::vector<int>({4, 5});
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; assign the initializer list directly
+  // CHECK-FIXES: V = {4, 5};
+}
+
+void count(std::vector<int> &V, size_type N) {
+  V = std::vector<int>(N);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; use 'clear' and 'resize' to reuse the existing storage
+  // CHECK-FIXES: V.clear(); V.resize(N);
+
+  // Not a statement of its own, so there is no room for two statements:
+  // diagnosed without a fix-it.
+  if (N)
+    V = std::vector<int>(N);
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: inefficient assignment from a temporary 'std::vector'; use 'clear' and 'resize'
+  // CHECK-FIXES: V = std::vector<int>(N);
+
+  // The count would be evaluated after 'clear()': diagnosed without a fix-it.
+  V = std::vector<int>(getCount());
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; use 'clear' and 'resize'
+  // CHECK-FIXES: V = std::vector<int>(getCount());
+}
+
+void direct(std::vector<int> &V, const std::vector<int> &Other,
+            std::vector<int> &&Temp) {
+  V = std::vector<int>(Other);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; assign the source directly to reuse the existing storage
+  // CHECK-FIXES: V = Other;
+
+  V = std::vector<int>(std::move(Temp));
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; assign the source directly
+  // CHECK-FIXES: V = std::move(Temp);
+}
+
+void destinations(Holder &H, size_type N) {
+  H.Items = std::vector<int>(N, 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: H.Items.assign(N, 1);
+
+  *H.Ptr = std::vector<int>(N, 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: (*H.Ptr).assign(N, 1);
+
+  getVector() = std::vector<int>(N, 2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: getVector().assign(N, 2);
+
+  H.Items = std::vector<int>(N);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: inefficient assignment from a temporary 'std::vector'; use 'clear' and 'resize'
+  // CHECK-FIXES: H.Items.clear(); H.Items.resize(N);
+
+  // The destination would be evaluated twice: diagnosed without a fix-it.
+  getVector() = std::vector<int>(N);
+  // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: inefficient assignment from a temporary 'std::vector'; use 'clear' and 'resize'
+  // CHECK-FIXES: getVector() = std::vector<int>(N);
+}
+
+void singleStatementBody(std::vector<int> &V, size_type N) {
+  if (N)
+    V = std::vector<int>(N, 0);
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: V.assign(N, 0);
+}
+
+void aliasing(std::vector<int> &V, Holder &H) {
+  // Iterators into the destination are diagnosed but not rewritten: 'assign'
+  // must not be given iterators into the container it replaces.
+  V = std::vector<int>(V.begin() + 1, V.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: V = std::vector<int>(V.begin() + 1, V.end());
+
+  // A count is computed before 'assign' runs, so it may mention the
+  // destination.
+  V = std::vector<int>(V.size(), 0);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: V.assign(V.size(), 0);
+
+  H.Items = std::vector<int>(H.Count, 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: H.Items.assign(H.Count, 1);
+
+  // With 'clear()' first, the count would be read from an emptied container.
+  H.Items = std::vector<int>(H.Items.size());
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: inefficient assignment from a temporary 'std::vector'; use 'clear' and 'resize'
+  // CHECK-FIXES: H.Items = std::vector<int>(H.Items.size());
+}
+
+void valueUsed(std::vector<int> &V, std::vector<int> &W, size_type N) {
+  // 'assign' does not yield the container, so the value of the assignment has
+  // to be discarded for the rewrite: diagnosed without a fix-it.
+  W = (V = std::vector<int>(N, 0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: W = (V = std::vector<int>(N, 0));
+}
+
+std::vector<int> &returned(std::vector<int> &V, size_type N) {
+  return V = std::vector<int>(N, 0);
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: return V = std::vector<int>(N, 0);
+}
+
+void otherContainers(std::deque<int> &D, std::list<int> &L,
+                     std::forward_list<int> &F, size_type N) {
+  D = std::deque<int>(N, 0);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::deque'; use 'assign'
+  // CHECK-FIXES: D.assign(N, 0);
+
+  L = std::list<int>(N, 0);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::list'; use 'assign'
+  // CHECK-FIXES: L.assign(N, 0);
+
+  F = std::forward_list<int>(N, 0);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::forward_list'; use 'assign'
+  // CHECK-FIXES: F.assign(N, 0);
+}
+
+void strings(std::string &S, const std::string &Other, const char *Chars,
+             size_type N) {
+  S = std::string(N, ' ');
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::basic_string'; use 'assign'
+  // CHECK-FIXES: S.assign(N, ' ');
+
+  S = std::string(Chars, N);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::basic_string'; use 'assign'
+  // CHECK-FIXES: S.assign(Chars, N);
+
+  S = std::string(Other, 1, 2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::basic_string'; use 'assign'
+  // CHECK-FIXES: S.assign(Other, 1, 2);
+
+  S = std::string(Other);
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: inefficient assignment from a temporary 'std::basic_string'; assign the source directly
+  // CHECK-FIXES: S = Other;
+
+  // A single argument of another type is a conversion, which is a different
+  // matter: no diagnostic.
+  S = std::string(Chars);
+}
+
+void notDiagnosed(std::vector<int> &V, size_type N, std::allocator<int> Alloc) {
+  // Default construction releases the storage; 'clear()' would keep it.
+  V = std::vector<int>();
+  V = std::vector<int>{};
+
+  // No temporary container is involved.
+  V = {};
+  V = {1, 2};
+
+  // An explicitly passed allocator has no counterpart in 'assign'.
+  V = std::vector<int>(N, 0, Alloc);
+
+  // Initializations are copy-elided since C++17; nothing to save.
+  std::vector<int> Init = std::vector<int>(N, 0);
+}
+
+void shrinkToFit(std::vector<int> &V, Holder &H) {
+  // Copying a container into itself is the idiom for trimming its capacity;
+  // there the temporary is the point, so there is no diagnostic.
+  V = std::vector<int>(V);
+  H.Items = std::vector<int>(H.Items);
+}
+
+struct Derived : std::vector<int> {
+  using std::vector<int>::operator=;
+};
+
+void derived(Derived &D, size_type N) {
+  // The destination's type differs from the temporary's: no diagnostic.
+  D = std::vector<int>(N, 0);
+}
+
+template <typename T>
+void dependent(std::vector<T> &V, size_type N) {
+  // Type-dependent: no diagnostic, including in instantiations.
+  V = std::vector<T>(N, T());
+}
+void instantiate(std::vector<int> &V) { dependent(V, 3); }
+
+#define ASSIGN_FILL(Dest, Count) Dest = std::vector<int>(Count, 0)
+void macro(std::vector<int> &V) {
+  // Diagnosed, but no fix-it: rewriting a macro expansion is unsafe.
+  ASSIGN_FILL(V, 3);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: inefficient assignment from a temporary 'std::vector'; use 'assign'
+  // CHECK-FIXES: ASSIGN_FILL(V, 3);
+}



More information about the cfe-commits mailing list