Created
July 24, 2011 15:41
-
-
Save farnoy/1102736 to your computer and use it in GitHub Desktop.
Shared resources in C++0x
This file contains 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
#include <iostream> | |
#include <string> | |
#include <memory> | |
struct Printer { | |
virtual void Print() = 0; | |
}; | |
struct StandardCoutPrinter : Printer { | |
std::weak_ptr<std::string> content; | |
StandardCoutPrinter(std::shared_ptr<std::string> text) { this->content = std::weak_ptr<std::string>(text); } | |
virtual void Print() { | |
std::cout << *this->content.lock() << std::endl; | |
} | |
}; | |
int main() { | |
// Shared string resource | |
std::shared_ptr<std::string> text_res(new std::string("Test")); | |
// Initialize printer class with a std::weak_ptr reference | |
// which tracks shared resource for changes in content | |
std::unique_ptr<StandardCoutPrinter> printer(new StandardCoutPrinter(text_res)); | |
// Use unmodified string resource | |
printer->Print(); | |
/// Change resource | |
// Assign new resource | |
*text_res = std::string("Test8"); | |
printer->Print(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment