After code review I want to say that your Shared_Ptr is wrong. It would create many copies of the same object but will delete only last one. Also move constructor is inefficient
pointer = new T(*p);This will crete new copy of variable stored in p. And only last Shared_Ptr in group will actually delete his own copy. So there:
a) memory leak
b) Different Shared_Ptr will always point to different objects. You cannot have two shared pointer pointing to same object, which defats its purpose.
I couldn't quite figure out how to deal with the move thing and returning by rvalue with the Make_shared. During the return from Make_shared the data get's destroyed and nothing gets passed. What you just said sounds like it isn't quite the right solution. Then again I may be misunderstanding.
Looking around several documentations it says that Make_shared returns a shared_ptr<T> type. So I just settle with this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
template <typename T>
Share<T> Make_shared(const T n = T())
{
Share<T> ret;
ret.pointer = new T(n);
ret.cnt = new size_t(1);
return ret;
}
int main()
{
Share<int> p = Make_shared<int>(5);
}
Would there be a memory leak here? I'm thinking that p is pointing to the object ret is pointing to and if p gets deleted, there shouldn't be a problem.
int main()
{
Share<int> p = Make_shared<int>(5);
p = Make_shared<int>(10);
}
first in would not be destroyed. You should handle this situation. To test such situations I recommend to make class which will output each construction and destruction.
And provide non-move constructors and assigment operator too!
Okay I'll add them in. The assignment operator is already redefined to handled that problem, unfortunately I copied it from the book. I also have std::couts all over the place to find out the construction and destruction, but I should get into a habit of utilizing class for that like you said, or functs.