Last active
December 23, 2015 01:58
-
-
Save bkuhns/6563448 to your computer and use it in GitHub Desktop.
In reply to http://stackoverflow.com/a/18803611/245869 "For a value type Foo, why does a shared_ptr<const Foo> act like a value type even though it is a pointer type?"
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 <memory> | |
#include "Foo.hpp" | |
#include "Bar.hpp" | |
int main() | |
{ | |
auto bar = Bar{}; | |
std::shared_ptr<const Foo> foo = bar.foo(); | |
std::cout << "Foo's num: " << foo->num() << std::endl; | |
bar.doSomething(); | |
std::cout << "Foo's num: " << foo->num() << std::endl; | |
// Output: | |
// Foo's num: 0 | |
// Foo's num: 5 | |
} |
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
class Bar { | |
public: | |
std::shared_ptr<const Foo> foo() const | |
{ | |
return foo_; | |
} | |
void doSomething() | |
{ | |
foo_->setNum(5); | |
} | |
private: | |
std::shared_ptr<Foo> foo_{std::make_shared<Foo>()}; | |
}; |
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
class Foo { | |
public: | |
int num() const | |
{ | |
return num_; | |
} | |
void setNum( int num ) | |
{ | |
num_ = num; | |
} | |
private: | |
int num_{0}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment