Skip to content

Instantly share code, notes, and snippets.

@bkuhns
Last active December 23, 2015 01:58
Show Gist options
  • Save bkuhns/6563448 to your computer and use it in GitHub Desktop.
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?"
#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
}
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>()};
};
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