Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

call to implicitly-deleted copy constructor



  • Hi guys
    this code generates an error "call to implicitly-deleted copy constructor"

    // profit.h
    
    class Profit : public QObject
    {
        Q_OBJECT
    
    public:
        explicit Profit(QObject *parent = nullptr);
    Q_INVOKABLE Profit parse(QString string);
    }
    
    // profit.cpp
    Profit Profit::parse(QString string)
    {
        QStringList pieces = string.split( ";" );
        Profit profit;
        return profit; // error here
    }
    

    Any idea how to fix that? Many thanks


  • Lifetime Qt Champion

    Hi,

    QObject based class are not copiable.

    You have to create an instance on the heap and return the corresponding pointer.



  • Thanks do you mean something like that? How to create it in the heap?

    Profit * Profit::parse(QString string)
    {
    QStringList pieces = string.split( ";" );
    Profit profit;
    profit.setDate(pieces.takeAt(0));
    profit.setMoney(pieces.takeAt(1).toDouble());
    return &profit;
    }

    Many thanks


  • Lifetime Qt Champion

    Not at all, you are returning a reference to local stack allocated object which means it's dangling as soon as you are back on the other side of the parse call because profit is destroyed when the method ends.

    Heap allocation: Profit *profit = new Profit;


  • Lifetime Qt Champion

    Hi
    but it looks a bit odd.
    Why does Profit's parse return another Profit instance?

    I would expect something like

    
    Profit p;
    p.parse("...");
    p.getDate() // use for something
    p.GetMoney()
    
    and not
    Profit p;
    Profit  *result = p.parse("...");
    result ->getDate()
    result ->GetMoney()
    delete result;// else you leak
    }
    

Log in to reply