最終更新日時(UTC):
が更新

履歴 編集

function
<memory>

std::polymorphic::代入演算子(C++26)

constexpr polymorphic& operator=(const polymorphic& other);                // (1)
constexpr polymorphic& operator=(polymorphic&& other) noexcept(see below); // (2)

概要

  • (1) : コピー代入。otherが保持する派生型のオブジェクトをディープコピーする。
  • (2) : ムーブ代入。otherから所有権を移す。

適格要件

効果

  • (1) : addressof(other) == thisであれば何もしない。そうでなければ、アロケータの伝播規則に従い、otherが保持するオブジェクトのコピーを*thisがもつようにする。otherが無効値状態であれば*thisも無効値状態にする。
  • (2) : addressof(other) == thisであれば何もしない。そうでなければ、アロケータの伝播規則に従い、otherから所有権を移すか、ムーブ構築する。

戻り値

*thisへの参照。

例外

  • (1) : 強い例外安全性を保証する。例外が送出された場合、*thisotherに影響はない。
  • (2) : 以下と等価なnoexcept指定を持つ:

noexcept(allocator_traits<Allocator>::propagate_on_container_move_assignment::value ||
         allocator_traits<Allocator>::is_always_equal::value)

#include <cassert>
#include <memory>

struct Base {
  virtual ~Base() = default;
  virtual int f() const { return 0; }
};
struct Derived : Base {
  int x = 42;
  Derived() = default;
  Derived(int x) : x(x) {}
  int f() const override { return x; }
};

int main()
{
  std::polymorphic<Base> a{std::in_place_type<Derived>, 1};
  std::polymorphic<Base> b{std::in_place_type<Derived>, 2};

  a = b;             // (1) コピー代入(派生型のディープコピー)
  assert(a->f() == 2);

  a = std::move(b);  // (2) ムーブ代入
  assert(a->f() == 2);
}

出力

バージョン

言語

  • C++26

処理系

関連項目

参照