Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
C++ move/copy constructor and assignment demo
//Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x64 // // The following sample shows when a move/copy constructor/assignment is used // based on the code sample from cppreference about rule of five. // Move ctors/assignments help saving memory/time when a value that is going // to be discarded after the ctor/assignment anyways is used to create/change something // else (e.g. when the rvalue contains a ressource that is transferred to the lvalue). #include <iostream> #include <afx.h> // Src: http://en.cppreference.com/w/cpp/language/rule_of_three#Rule_of_five class rule_of_five { char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block public: rule_of_five(const char* arg) : cstring(new char[std::strlen(arg)+1]) // allocate { std::strcpy(cstring, arg); // populate std::cout << "ctor allocate " << cstring << std::endl; } ~rule_of_five() { if(cstring){ std::cout << "dtor " << cstring << std::endl; delete[] cstring; // deallocate } else std::cout << "dtor, already deleted" << std::endl; } rule_of_five(const rule_of_five& other) // copy constructor { std::cout << "ctor copy - constructing with copy of " << other.cstring << std::endl; cstring = new char[std::strlen(other.cstring) + 1]; std::strcpy(cstring, other.cstring); } rule_of_five(rule_of_five&& other) : cstring(other.cstring) // move constructor { std::cout << "ctor move " << cstring << " to me" << std::endl; other.cstring = nullptr; } rule_of_five& operator=(const rule_of_five& other) // copy assignment { std::cout << "assign copy of " << other.cstring << " to " << cstring << std::endl; char* tmp_cstring = new char[std::strlen(other.cstring) + 1]; std::strcpy(tmp_cstring, other.cstring); delete[] cstring; cstring = tmp_cstring; return *this; } rule_of_five& operator=(rule_of_five&& other) // move assignment { std::cout << "assign move: move " << other.cstring << " to " << cstring << std::endl; if(this!=&other) // prevent self-move { delete[] cstring; cstring = other.cstring; other.cstring = nullptr; } return *this; } }; // some method that retunrs some rule_of_five object rule_of_five createSome(int a){ switch(a) { case 1: return rule_of_five("one"); default: return rule_of_five("default"); } } int main() { // ctors rule_of_five a("abc"); // ctor alloc rule_of_five b = a; // ctor copy rule_of_five f = rule_of_five(createSome(1)); // ctor move // assignment a = rule_of_five("asdf"); // assign move, dtor on rval b = a; // assign copy }
run
|
edit
|
history
|
help
0
error_check
infix to postfix v 1.0
find vs at
Problem_onoff_3
multiplie linked list numbers
MSVC14 <experimental/generator> header
Regex failure
DCapSurfaceDesc
Copy initialization: overload resolution issue
Memory example