Home > OS >  Why am I not able to use the push_back() function in the following c code?
Why am I not able to use the push_back() function in the following c code?

Time:12-20

I'm trying to create a vector of structs - that I'll use later in other functions - for a structure called customer. However, when I use the push_back() function, I get the following error

In template: call to implicitly-deleted copy constructor of 'customer'

Can anyone explain why I receive this error, please?

Here's the part of the code related to my problem:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

struct cartitem{
    //members of the struct
};

struct customer{
    string name;
    string arrival_time;
    float total_price = 0.0;
    vector<cartitem> cart;
    fstream mycart;
};

vector<customer> Customers;

static customer newCustomer(string cname, string arrtime){
    customer b;
    b.name = cname;
    b.arrival_time = arrtime;
    Customers.push_back(b);
    return b;
};

CodePudding user response:

When you call push_back(), you are pushing a copy of b. However, customer has an fstream member, which does not support copying (only moving), so the compiler implicitly deletes customer's copy constructor, which is what the push_back() is trying to call. That is why you get the error.

CodePudding user response:

As in Remy's post, push_back makes a copy.

Create a constructor and try:

customer &newCustomer(const string &cname, const string &arrtime){
    return Customers.emplace_back({cname, arrtime}); // requires C  17 or you can return Customers.back()
};

Th example here should be useful: https://en.cppreference.com/w/cpp/container/vector/emplace_back

  • Related