Rocky (Po-Hsun Tseng)
  • NEW!
    NEW!  Connect Ideas Across Notes
    Save time and share insights. With Paragraph Citation, you can quote others’ work with source info built in. If someone cites your note, you’ll see a card showing where it’s used—bringing notes closer together.
    Got it
      • Create new note
      • Create a note from template
        • Sharing URL Link copied
        • /edit
        • View mode
          • Edit mode
          • View mode
          • Book mode
          • Slide mode
          Edit mode View mode Book mode Slide mode
        • Customize slides
        • Note Permission
        • Read
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Write
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invite by email
        Invitee

        This note has no invitees

      • Publish Note

        Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

        Your note will be visible on your profile and discoverable by anyone.
        Your note is now live.
        This note is visible on your profile and discoverable online.
        Everyone on the web can find and read all notes of this public team.

        Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Explore these features while you wait
        Complete general settings
        Bookmark and like published notes
        Write a few more notes
        Complete general settings
        Write a few more notes
        See published notes
        Unpublish note
        Please check the box to agree to the Community Guidelines.
        View profile
      • Commenting
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Suggest edit
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
      • Emoji Reply
      • Enable
      • Versions and GitHub Sync
      • Note settings
      • Note Insights New
      • Engagement control
      • Make a copy
      • Transfer ownership
      • Delete this note
      • Save as template
      • Insert from template
      • Import from
        • Dropbox
        • Google Drive
        • Gist
        • Clipboard
      • Export to
        • Dropbox
        • Google Drive
        • Gist
      • Download
        • Markdown
        • HTML
        • Raw HTML
    Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
    Create Create new note Create a note from template
    Menu
    Options
    Engagement control Make a copy Transfer ownership Delete this note
    Import from
    Dropbox Google Drive Gist Clipboard
    Export to
    Dropbox Google Drive Gist
    Download
    Markdown HTML Raw HTML
    Back
    Sharing URL Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    Customize slides
    Note Permission
    Read
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Write
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Move Constructors without `noexcept` ```c++ #include <string> #include <iostream> class Person { private: std::string name; public: Person(const char* n) : name{n} { } std::string getName() const { return name; } // print out when we copy or move: Person(const Person& p) : name{p.name} { std::cout << "COPY " << name << '\n'; } Person(Person&& p) : name{std::move(p.name)} { std::cout << "MOVE " << name << '\n'; } //... }; int main() { std::vector<Person> coll{ "Wolfgang Amadeus Mozart", "Johann Sebastian Bach", "Ludwig van Beethoven" }; std::cout << "capacity: " << coll.capacity() << '\n'; coll.push_back("Pjotr Iljitsch Tschaikowski"); } ``` The output of the program is as follows: ``` COPY Wolfgang Amadeus Mozart COPY Johann Sebastian Bach COPY Ludwig van Beethoven capacity: 3 MOVE Pjotr Iljitsch Tschaikowski COPY Wolfgang Amadeus Mozart COPY Johann Sebastian Bach COPY Ludwig van Beethoven ``` The following diagrams demonstrate how does `push_back()` work internally: * Step 1: ![image](https://hackmd.io/_uploads/S1SHoWLCgl.png =50%x) * Step 2: ![image](https://hackmd.io/_uploads/SylzLj-IAex.png =50%x) * Step 3: ![image](https://hackmd.io/_uploads/S1SwoWLAgg.png =50%x) The reason that vector reallocation does not use move semantics is the strong exception handling guarantee we give for `push_back()`: When an exception is thrown in the middle of the reallocation of the vector the C++ standard library guarantees to roll back the vector to its previous state. Please see [STL container with noexcept](/9vytxRpLQGWMiwLdUs0ntA) for more details. # Move Constructors with `noexcept` When we guarantee that the move constructor never throw: ```c++ Person(Person&& p) noexcept : name{std::move(p.name)} { std::cout << "MOVE " << name << '\n'; } ``` The output will be: ``` COPY Wolfgang Amadeus Mozart COPY Johann Sebastian Bach COPY Ludwig van Beethoven capacity: 3 MOVE Pjotr Iljitsch Tschaikowski MOVE Wolfgang Amadeus Mozart MOVE Johann Sebastian Bach MOVE Ludwig van Beethoven ``` * Step 1: ![image](https://hackmd.io/_uploads/Hke9bG8Rgg.png =50%x) * Step 2: ![image](https://hackmd.io/_uploads/Hyi5WfI0el.png =50%x) * Step 3: ![image](https://hackmd.io/_uploads/S16ibGLAll.png =50%x) Please see [emplace_back vs. push_back](/GRwsNRl_QiS4GoyYEC-TCA) for more details. # Details of `noexcept` Declarations * See [noexcept specifier](/h3xGM3n7QIiRzjUibx7_0Q). * The move constructor usually does not output anything; therefore, in general when members do not throw, we can give the guarantee not to throw for the move constructor as a whole. * If you implement a move constructor, you should declare whether and when it guarantees not to throw. * If you do not have to implement the move constructor, you do not have to specify anything at all. ## `noexcept` for Copying and Moving Special Member Functions * `noexcept` condition is generated for generated special member functions. * `noexcept` condition is not generated for user-implement special member functions. * Before C\+\+20, if the generated and specified `noexcept` conditions contradict, the defined function was deleted. Since C++20, the specified `noexcept` condition takes precedence over the generated one. ```c++ class C { public: // guarantees not to throw (OK since C++20) C(const C&) noexcept = default; // specifies that it might throw (OK since C++20) C(C&&) noexcept(false) = default; }; ``` ## `noexcept` for Destructors By rule, destructors always guarantee not to throw by default. This applies to both generated and implemented destructors. For example: ```c++ class B { private: std::string s; public: ~B() { // automatically always declared as ~B() noexcept } }; ``` With `noexcept(false)`, you can declare them without this guarantee, but that usually never makes any sense because several guarantees of the C++ standard library are based on the fact that destructors never throw. # `noexcept` Declarations in Class Hierarchies * Following the rules of the C++ standard, we should declare it not to throw when all base classes and all member types do not throw on a move construction. The general pattern would be as follows: ```c++ class Ancestor { ... }; class Descendant : public Ancestor { MemType member; Descendant(Descendant&&) noexcept(std::is_nothrow_move_constructible_v<Ancestor> && std::is_nothrow_move_constructible_v<MemType>); }; ``` * The move assignment operator might use the same pattern but note that the move assignment operator should be [deleted](https://hackmd.io/OIrF4_RqSC-_urbcqGdHDQ#Avoid-Defining-Assignment-Opeators-in-an-Abstract-Base-Class) in polymorphic types anyway, which means that there is usually no need to implement them in derived classes. * Note that the type trait `std::is_nothrow_move_constructible<>` always yields false because it also checks whether you can create an object of this type with the move constructor, which is not possible for abstract types. * The solution is to implement a non-abstract wrapper: ```c++ #include <iostream> #include <vector> #include <type_traits> template<typename Base> struct Wrapper : Base { using Base::Base; // implement all possibly wrapped pure virtual functions: // --> Make Wrapper is not an abstract class void print() const {} }; template<typename T> static constexpr inline bool is_nothrow_movable_v = std::is_nothrow_move_constructible_v<Wrapper<T>>; class Base { private: std::string id; public: Base() = default; // pure virtual function (forces abstract base class) virtual void print() const = 0; virtual ~Base() = default; protected: // protected copy and move semantics (also forces abstract base class): Base(const Base&) = default; Base(Base&&) = default; // disable assignment operator (due to the problem of slicing): Base& operator= (Base&&) = delete; Base& operator= (const Base&) = delete; }; class Drv : public Base { public: void print() const override { std::cout << "Drv::print()\n"; } Drv() = default; Drv(const Drv& rhs) { if (this == &rhs) return; std::cout << "COPY\n"; } Drv(Drv&& rhs) noexcept(is_nothrow_movable_v<Base>) //Drv(Drv&& rhs) noexcept(std::is_nothrow_move_constructible_v<Base>) { if (this == &rhs) return; std::cout << "MOVE\n"; } }; int main() { std::cout << std::boolalpha; std::cout << "std::is_nothrow_move_constructible_v<Base>: " << std::is_nothrow_move_constructible_v<Base> << '\n'; std::cout << "is_nothrow_movable_v<Base> : " << is_nothrow_movable_v<Base> << '\n'; std::vector<Drv> v; v.reserve(2); v.push_back(Drv{}); v.push_back(Drv{}); v.push_back(Drv{}); } ``` * Using `is_no_throw_movable_v` in `Drv`'s move constructor yields: ``` MOVE MOVE MOVE MOVE MOVE ``` * Using `std::is_nothrow_move_constructible_v` in `Drv`'s move constructor yields: ``` MOVE MOVE MOVE COPY COPY ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully