Category:c++
Article From:https://www.cnblogs.com/zhangkele/p/9060883.html

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(other.name)), country(std::move(other.country)), 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 << president.name << " was elected president of "
                  << president.country << " in " << president.year << ".\n";
    }
    for (President const& president: reElections) {
        std::cout << president.name << " was re-elected president of "
                  << president.country << " in " << president.year << ".\n";
    }
}
Copy code

Output:

Copy code
emplace_back:
I am being constructed.
 
push_back:
I am being constructed.
I am being moved.
 
Contents:
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 *