Created
July 1, 2016 00:27
-
-
Save Verdagon/84dad1a42c376709432406339f7dea00 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SteeringWheel { | |
public: | |
boolean fuzzy; | |
SomeExternalResource * resource; | |
// copy constructor | |
SteeringWheel(const SteeringWheel & other) { | |
fuzzy = other.fuzzy; | |
resource = new SomeExternalResource(); | |
resource->copyContentsFrom(other.resource); | |
} | |
// move constructor, thats an rvalue reference | |
SteeringWheel(SteeringWheel && other) { | |
fuzzy = other.fuzzy; | |
resource = other.resource; | |
other.resource = NULL; | |
} | |
// destructor, which was coded to expect its organs being harvested | |
~SteeringWheel() { | |
if (resource != NULL) { | |
delete resource; | |
} | |
} | |
}; | |
// example of the c way | |
void doThings(SteeringWheel * derpWheel) { | |
// stuff | |
// change derpWheel's fuzzy to false | |
// now derpWheel dies | |
} | |
void makeMeAWheel(SteeringWheel ** steeringWheelPtrPtr) { | |
*steeringWheelPtrPtr = new SteeringWheel(true, new SomeExternalResource()); | |
} | |
int main() { | |
SteeringWheel * coolWheel = NULL; | |
makeMeAWheel(&coolWheel); | |
doThings(coolWheel); | |
// myWheel dies here | |
} | |
// example of rvalue references / copies being good | |
void doThings(SteeringWheel derpWheel, function<void(float)> progressCallback) { | |
// stuff | |
// derpWheel fuzzy is still true | |
progressCallback(.1); | |
// derpWheel fuzzy is still true good | |
// change derpWheel's fuzzy to false | |
progressCallback(.2); | |
progressCallback(.4); | |
// now derpWheel dies | |
} | |
SteeringWheel makeMeAWheel() { | |
return SteeringWheel(true, new SomeExternalResource()); | |
} | |
int main() { | |
SteeringWheel myWheel = makeMeAWheel(); | |
// function<void(float)> has: SteeringWheel & | |
doThings(std::move(myWheel), [&](float progress){ | |
// compiler will complain because myWheel was already doomed | |
myWheel.fuzzy = false; | |
cout << "Progress: " << progress * 100 << endl; | |
}); | |
// myWheel dies here | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment