C++11 emplace_back on vector?

前端 未结 8 522
借酒劲吻你
借酒劲吻你 2020-12-02 14:58

Consider the following program:

#include 
#include 

using namespace std;

struct T
{
    int a;
    double b;
    string c;
};

         


        
相关标签:
8条回答
  • 2020-12-02 15:40

    Of course, this is not an answer, but it shows an interesting feature of tuples:

    #include <string>
    #include <tuple>
    #include <vector>
    
    using namespace std;
    
    using T = tuple <
        int,
        double,
        string
    >;
    
    vector<T> V;
    
    int main()
    {
        V.emplace_back(42, 3.14, "foo");
    }
    
    0 讨论(0)
  • 2020-12-02 15:47

    You need to explicitly define a ctor for the class:

    #include <string>
    #include <vector>
    
    using namespace std;
    
    struct T
    {
        int a;
        double b;
        string c;
    
        T(int a, double b, string &&c) 
            : a(a)
            , b(b)
            , c(std::move(c)) 
        {}
    };
    
    vector<T> V;
    
    int main()
    {
        V.emplace_back(42, 3.14, "foo");
    }
    

    The point of using emplace_back is to avoid creating a temporary object, which is then copied (or moved) to the destination. While it is also possible to create a temporary object, then pass that to emplace_back, it defeats (at least most of) the purpose. What you want to do is pass individual arguments, then let emplace_back invoke the ctor with those arguments to create the object in place.

    0 讨论(0)
提交回复
热议问题