Last active
August 29, 2015 14:05
-
-
Save lilianmoraru/0d03eb63b2a9e6505656 to your computer and use it in GitHub Desktop.
C++11 Example
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
//For demonstration purposes we move reverse into a separate function | |
// In C++98 - this would make a deep copy then throw the original | |
// In C++11 - It will detect that a temporary is passed. It uses move semantics automatically. | |
// Copies the pointer and takes ownership of the buffer. | |
// Doesn't do a shallow copy or deep copy. | |
// There is no need to implicitly tell the compiler what to do with a temporary data, | |
// it's error prone while the compiler knows | |
// better and the case is very simple for the compiler to detect. | |
// If the user wants, he can tell it explicitly with "string&& s" | |
string reverse_string(string s) { | |
reverse(s.begin(), s.end()); | |
return s; //Here same thing happens in C++11. | |
} | |
int main() { | |
vector<future<string>> functions; | |
functions.push_back(async([] { return reverse_string( " olleH"); })); | |
functions.push_back(async([] { return reverse_string(" nredom"); })); | |
functions.push_back(async([] { return reverse_string( "++C"); })); | |
for (auto& elem : functions) { | |
cout << elem.get(); //.get() - waiting for the function to finish. | |
} | |
} | |
//For "async" the compiler will detect if the operations are complex | |
//and will choose between executing the code inside the same | |
//thread or create a new one. It also can be explicitly selected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment