Article From:

Introducing the right value reference, transferring the constructor, and transferring the copy operator.before,When push_back () is usually used to add a right value element (temporary object) into the container, the constructor is first called to construct the temporary object, and then a copy constructor is needed to put the temporary object into the container. The original temporary variable was released. The problem caused by this is temporaryThe resources of the variable application are wasted. It


c++11A right – value reference is introduced.Move Constructor(Please look at it.after,push_back()When the value is right, the constructor and the transfer constructor are called.。 


Here it is.The space for further optimization is to use emplace_back.

emplace_back   An element is added to the end of the container, which is originally constructed.There is no need to trigger copy construction and transfer construction。Moreover, the form of the call is more concise, initializing the members of the temporary object directly based on the parameters. It emplace_back avoidpush_backRequired when usingExtra copy or mobile operation

Copy code
#include <vector>
#include <string>
#include <iostream>
struct President
    std::string name;
    std::string country;
    int year;
    President(std::string p_name, std::string p_country, int p_year)
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)
        std::cout << "I am being constructed.\n";
    President(President&& other)
        : name(std::move(, country(std::move(, year(other.year)
        std::cout << "I am being moved.\n";
    President& operator=(const President& other) = default;
int main()
    std::vector<President> elections;
    std::cout << "emplace_back:\n";
    elections.emplace_back("Nelson Mandela", "South Africa", 1994);
    std::vector<President> reElections;
    std::cout << "\npush_back:\n";
    reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));
    std::cout << "\nContents:\n";
    for (President const& president: elections) {
        std::cout << << " was elected president of "
                  << << " in " << president.year << ".\n";
    for (President const& president: reElections) {
        std::cout << << " was re-elected president of "
                  << << " in " << president.year << ".\n";
Copy code


Copy code
I am being constructed.
I am being constructed.
I am being moved.
Nelson Mandela was elected president of South Africa in 1994.
Franklin Delano Roosevelt was re-elected president of the USA in 1936.
Copy code



Leave a Reply

Your email address will not be published. Required fields are marked *