I am trying to write Manager class which is going to manage multiple instances of Test Class. I should be able to destroy an instance of Test Class by calling mng.drop(shared pointer to the instance to be dropped).
I am not supposed to use unique_ptr How do I implement using shared_ptr
#include <iostream>
#include <iomanip>
#include <memory>
#include <set>
#define DEBUG ON
#ifdef DEBUG
#define DEBUG_MSG(str) do {std::cout << std::setw(75) << std::left << __FUNCTION__ \
<< std::setw(3) << std::left << ":" << std::setw(5) << std::left << __LINE__ \
<< std::setw(5) << std::left << ":"\
<< std::left << str \
<< std::endl;} while( false )
#else
#define DEBUG_MSG(str) do { } while ( false )
#endif
class Test{
public:
Test(int i) : i_(i){
DEBUG_MSG("Constructor");
}
~Test(){
DEBUG_MSG("Destructor");
}
int getI() { return i_; }
void setI(int i){ i_ = i; }
void fn()
{
DEBUG_MSG("Do Something Here");
}
private:
int i_;
};
using sharedPtr = std::shared_ptr < Test >;
class Manager{
public:
sharedPtr createTest(int i)
{
auto ptr = std::make_shared<Test>(i);
list_.insert(ptr);
return ptr;
}
void drop(sharedPtr ptr)
{
list_.erase(ptr);
}
private:
std::set<sharedPtr> list_;
};
int main()
{
Manager mng;
auto test = mng.createTest(50);
DEBUG_MSG("test : " << test.use_count());
test->fn();
mng.drop(test);
DEBUG_MSG("test : " << test.use_count());
system("Pause");
return 0;
}
As it can be seen : in my code when I call mng.drop(test) - still the reference count is 1, hence object is not destroyed.
Test::Test : 22 : Constructor
main : 62 : test : 2
Test::fn : 31 : Do Something Here
main : 65 : test : 1
Press any key to continue . . .
EDIT
My requirement: Manager Class should hold shared_ptr to all Test instances active; It should able to create and destroy Test instance