dimanche 6 juin 2021

why move-only object can not add explicit keyword?

code is below :

#include <iostream>
class MacroObject {
public :
MacroObject() = default;

MacroObject(const MacroObject&) = delete ;
MacroObject& operator=(const MacroObject&) = delete;

explicit MacroObject(MacroObject&&)=default;
MacroObject& operator=(MacroObject&&)=default;

int init(){return 0;}
int get(){return 0;}
};

MacroObject getObj(){
 MacroObject obj;
obj.init();
return obj;
}

int main(){

MacroObject obj{getObj()};
std::cout << obj.get() << std::endl;
return 0;
}

named test.cpp

use " g++ -std=c++11 test.cpp" (g++ 4.8.5) make error message :


" test.cpp: In function 'MacroObject getObj()': test.cpp:19:8: error: use of deleted function 'MacroObject::MacroObject(const MacroObject&)' return obj; ^ test.cpp:6:1: error: declared here MacroObject(const MacroObject&) = delete ; ^ "


When I remove explicit , it is ok. So my question is : why g++ use deleted copy-ctor other than move-ctor ?

Aucun commentaire:

Enregistrer un commentaire