Move Constructors
A move constructor enables an object to take ownership of resources from a temporary (rvalue) object, avoiding expensive deep copies. Its signature uses an rvalue reference.
main.cpp
1234567891011121314151617181920212223242526272829303132333435363738394041#include <iostream> #include <cstring> class StringHolder { public: char* data; // Constructor StringHolder(const char* str) { data = new char[std::strlen(str) + 1]; std::strcpy(data, str); std::cout << "Constructed: " << data << std::endl; } // Move constructor StringHolder(StringHolder&& other) noexcept { data = other.data; other.data = nullptr; std::cout << "Move constructed." << std::endl; } // Destructor ~StringHolder() { if (data) { std::cout << "Destroyed: " << data << std::endl; delete[] data; } else std::cout << "Destroyed: nullptr" << std::endl; } }; int main() { StringHolder a("hello"); StringHolder b(std::move(a)); }
In the example above, the move constructor transfers the resource pointer and nulls out the source, ensuring only one object manages the resource.
A move constructor is called when an object is initialized from a temporary (rvalue) of the same type, such as when returning a local object from a function or using std::move.
After the move, the source object should be left in a valid but unspecified state. Typically, pointers are set to nullptr.
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion
Génial!
Completion taux amélioré à 10
Move Constructors
Glissez pour afficher le menu
A move constructor enables an object to take ownership of resources from a temporary (rvalue) object, avoiding expensive deep copies. Its signature uses an rvalue reference.
main.cpp
1234567891011121314151617181920212223242526272829303132333435363738394041#include <iostream> #include <cstring> class StringHolder { public: char* data; // Constructor StringHolder(const char* str) { data = new char[std::strlen(str) + 1]; std::strcpy(data, str); std::cout << "Constructed: " << data << std::endl; } // Move constructor StringHolder(StringHolder&& other) noexcept { data = other.data; other.data = nullptr; std::cout << "Move constructed." << std::endl; } // Destructor ~StringHolder() { if (data) { std::cout << "Destroyed: " << data << std::endl; delete[] data; } else std::cout << "Destroyed: nullptr" << std::endl; } }; int main() { StringHolder a("hello"); StringHolder b(std::move(a)); }
In the example above, the move constructor transfers the resource pointer and nulls out the source, ensuring only one object manages the resource.
A move constructor is called when an object is initialized from a temporary (rvalue) of the same type, such as when returning a local object from a function or using std::move.
After the move, the source object should be left in a valid but unspecified state. Typically, pointers are set to nullptr.
Merci pour vos commentaires !