Hi All,
Here i am with another question . When i execute the code below the destructor in Stone is called twice . Why?
In main set<Stone> stones = bag.letMeSeeStones();
is coming from reference hence "stones" should not be treated like a local object.
#include <iostream>
#include <set>
using namespace std;
class Stone{
public:
Stone(const double mg):weight(mg){}
friend bool operator<(const Stone &s1,const Stone &s2) {
return s1.weight <s2.weight;
}
~Stone(){
cout << " I am no more a stone " <<endl;
}
private:
double weight;
};
class BagOfStone{
public:
void keepStone(const Stone &stone){
stones.insert(stone);
}
set<Stone>& letMeSeeStones(){
return stones;
}
private:
set<Stone> stones;
};
int main(int argc,char** argv){
BagOfStone bag;
Stone *heavyone = new Stone(10.0);
bag.keepStone(*heavyone);
set<Stone> stones = bag.letMeSeeStones();
return 0;
}
If want to achieve my goal than i can modify like this
#include <iostream>
#include <set>
using namespace std;
class Stone{
public:
Stone(const double mg):weight(mg){}
friend bool operator<(const Stone &s1,const Stone &s2) {
return s1.weight <s2.weight;
}
~Stone(){
cout << " I am no more a stone " <<endl;
}
private:
double weight;
};
class BagOfStone{
public:
void keepStone(const Stone &stone){
stones.insert(stone);
}
set<Stone>* letMeSeeStones(){
return &stones;
}
private:
set<Stone> stones;
};
int main(int argc,char** argv){
BagOfStone bag;
Stone *heavyone = new Stone(10.0);
bag.keepStone(*heavyone);
set<Stone> *stones = bag.letMeSeeStones();
return 0;
}
I hope there would not be any difference in the behavior of above two program. I would appreciate if any one can explain why there should be difference and what could be repercussion if there would not be any difference in behavior.
Thanks,
Shailendra