我想使用std :: vector.push_bask在for循环中存储20个shared_ptr。 但从输出结果来看:它似乎只推了一个。 和vector :: push_back> 20次按设计工作。
有些人可以帮助我吗?
class IObserver{
public:
int virtual notify() = 0;
};
class CAdsUser
{
public:
int do_ads() {cout << __FUNCTION__<<endl;m_observer->notify(); return 0;}
CAdsUser(tr1::shared_ptr<IObserver> b):m_observer(b){cout << __PRETTY_FUNCTION__<<endl;};
~CAdsUser() {cout << __PRETTY_FUNCTION__<<endl;}
private:
tr1::shared_ptr<IObserver> m_observer;
};
class CMgr:public IObserver
{
public:
int virtual notify() { cout << __PRETTY_FUNCTION__<<endl; return 0;};
virtual ~CMgr(){cout << __PRETTY_FUNCTION__<<endl;};
};
using namespace std;
typedef vector<tr1::shared_ptr<CAdsUser> >VecType;
int main() {
tr1::shared_ptr<CMgr> g(new CMgr());
VecType m_online_user;
int i = 0;
for(i = 0; i < 20; i++);
{
tr1::shared_ptr<CAdsUser> ads_temp(new CAdsUser(g));
cout <<&ads_temp<<endl;
m_online_user.push_back((ads_temp));
//m_online_user.insert(m_online_user.begin(),1,ads_temp);
}
tr1::shared_ptr<CAdsUser> ads_temp1(new CAdsUser(g));
cout <<&ads_temp1<<endl;
m_online_user.push_back(ads_temp1);
/// CAdsUser *p = m_online_user[7];
VecType::iterator vi;
for(vi = m_online_user.begin();vi != m_online_user.end(); vi++)
(*vi)->do_ads();
vector<tr1::shared_ptr<string> > test_string;
for(i = 0; i< 20; i++)
{
tr1::shared_ptr<string> temp(new string());
temp->append("sdfsdfsfd");
test_string.push_back(temp);
}
vector<tr1::shared_ptr<string> >::iterator vs;
for(vs = test_string.begin();vs != test_string.end(); vs++)
cout<<*(*vs)<<endl;
return 0;
}
节目输出:
CAdsUser::CAdsUser(std::tr1::shared_ptr<IObserver>)
0xbfbf3084
CAdsUser::CAdsUser(std::tr1::shared_ptr<IObserver>)
0xbfbf30a0
do_ads
virtual int CMgr::notify()
do_ads
virtual int CMgr::notify()
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
sdfsdfsfd
CAdsUser::~CAdsUser()
CAdsUser::~CAdsUser()
virtual CMgr::~CMgr()
答案 0 :(得分:5)
for(i = 0; i < 20; i++);
// ^ this little guy is killing you
删除;
,你有一个空体的for循环。