mardi 7 juillet 2020

Trying to Implement Move Constructor to replace Copy Constructor

I was wondering if someone could look at the following code and tell me where I'm going wrong. The error message I'm getting is:

C2280 attempting to reference a deleted function

I'm trying to implement a "Move Constructor" that will be better than the regular Copy Constructor. If anyone could help me I will be eternally grateful! Thanks in advance!

#include <string>
#include <vector>

#include <iostream>
struct Item
{
    //Item attributes
    std::string sItemName;
    double *dSalePrice;
    int *iQuantitySold;
    
    //Constructor which uses initalisation list to create true initalization, as opposed to initalising in the body of the constructor which isn't true initalisation.
    Item(std::string sInitItemName, double dInitSalePrice, int iInitQuantitySold) //initalisation list
    {
        sItemName = sInitItemName;
        dSalePrice = new double;
        iQuantitySold = new int;

        *dSalePrice = dInitSalePrice;
        *iQuantitySold = iInitQuantitySold;
    }
    Item(const Item& objSource)
        :Item(objSource.sItemName, *objSource.dSalePrice, *objSource.iQuantitySold)
    {

        std::cout << "The copy constructor is being called.\n";

    }
//Problems occur when implementing this function here
    Item(Item&& objSource) noexcept
        :sItemName(objSource.sItemName),dSalePrice(objSource.dSalePrice), iQuantitySold(objSource.iQuantitySold)
    {
        
        objSource.dSalePrice = nullptr;
        objSource.iQuantitySold = nullptr;
    }
    ~Item() {
        delete dSalePrice;
        delete iQuantitySold;
    }

};

int main(){
std::vector<Item>vecOfItems;
Item newItem("New Item",32.23,43);
vecOfItems.push_back(newItem);
}

Aucun commentaire:

Enregistrer un commentaire