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
123456789101112131415161718192021222324252627282930313233343536373839#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.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Fantastisk!
Completion rate forbedret til 10
Move Constructors
Sveip for å vise menyen
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
123456789101112131415161718192021222324252627282930313233343536373839#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.
Takk for tilbakemeldingene dine!