Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    [C++] Rvalue references e move constructor

    Ciao a tutti,
    sto cercando di capire le rvalue references e i move constructor e pensavo di averli compresi, ma andando a scrivere un banale codice come questo non mi torna più niente.

    codice:
    struct foo {
        foo(const unsigned ID = 0) : ID(new unsigned(ID)){
            std::cout << " Constructor called.\n";
        }
        foo(const foo& other) : ID(new unsigned(*(other.ID))) {
            std::cout << " Copy constructor called.\n";
        }
        foo(foo&& other) : ID(other.ID) {
            other.ID = NULL;
            std::cout << " Move constructor called.\n";
        }
        ~foo() {
            delete ID;
        }
        foo operator+(const foo& other) {
            return foo(*ID + *(other.ID));
        }
    
        unsigned* ID;
    };
    
    int main()
    {
        foo a(2);
        foo b(a);
        foo c(a + b);
        return 0;
    }
    Il problema è che quando istanzio c, dovrebbe venir richiamato il move constructor ma non è così. L'operatore + dovrebbe restituire un oggetto temporaneo e quindi un rvalue, ma a quanto pare non è così...

  2. #2
    Utente di HTML.it L'avatar di shodan
    Registrato dal
    Jun 2001
    Messaggi
    2,381
    Nel tuo caso il compilatore applica la return value optimization, per cui costruisce il valore direttamente in uscita.
    La move semantics (eventualmente) si applica quando restituisci l'oggetto per valore:
    codice:
    foo operator+(const foo& other) {
            unsigned tmp = *ID + *(other.ID);
            foo ret(tmp);
            return ret;
        }
    This code and information is provided "as is" without warranty of any kind, either expressed
    or implied, including but not limited to the implied warranties of merchantability and/or
    fitness for a particular purpose.

  3. #3
    Ho provato anche il codice che hai postato, ma mi effettua la return value optimization lo stesso.
    Comunque grazie per la spiegazione.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.