Skip to content

Instantly share code, notes, and snippets.

@farnoy
Created July 24, 2011 15:41
Show Gist options
  • Save farnoy/1102736 to your computer and use it in GitHub Desktop.
Save farnoy/1102736 to your computer and use it in GitHub Desktop.
Shared resources in C++0x
#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