我想根据用户输入的字符串分配堆上的对象,但我无法访问函数外部的指针或对象,尽管它们在堆上。同样,我试图使用唯一的指针来分配它们,但我仍然得到一个错误,说“未声明”等。
如何创建这些对象,用户可以同时创建8个对象,单词之间留有空格。(例如“雪崩工具箱纸偶”等)?
string user_input;
getline(cin, user_input);
istringstream iss(user_input);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(vec));
for(int i=0; i<8; i++)
{
if(vec.at(i)=="Avalanche")
{
Avalanche *avalanche = new Avalanche(5);
std::unique_ptr<Avalanche> ptr(new Avalanche(5)); // even tried using unique pointer.
cout<<"Avalanche: "<<avalanche->c_game<<endl;
}
else if(vec.at(i)=="Bureaucrat")
{
Bureaucrat *bureaucrat = new Bureaucrat(5);
cout<<"Bureaucrat: "<<bureaucrat->c_game<<endl;
}
else if(vec.at(i)=="Toolbox")
{
Toolbox *toolbox = new Toolbox(5);
cout<<"Toolbox: "<<toolbox->c_game<<endl;
}
else if(vec.at(i)=="Crescendo")
{
Crescendo *crescendo = new Crescendo(5);
cout<<"Crescendo: "<<crescendo->c_game<<endl;
}
else if(vec.at(i)=="Paperdoll")
{
Paperdoll *paperdoll = new Paperdoll(5);
cout<<"Paperdoll: "<<paperdoll->c_game<<endl;
}
else if(vec.at(i)=="FistfullODollars")
{
Fistfullodollars *fistfullodollars = new Fistfullodollars(5);
cout<<"FistfullOdollars: "<<fistfullodollars->c_game<<endl;
}
}
cout<<ptr.c_game<<endl; // give an error not declared发布于 2015-08-24 00:17:34
您的对象生存期受其作用域的限制。在你的例子中,作用域在两个最接近的{}内。您需要记住,当您有一个指向已分配内存的(智能)指针时,您实际上有两个对象-一个是您的(智能)指针,另一个是指针所指向的对象。当指针超出范围时,您不能再通过此指针引用实际的对象。如果没有其他指针指向这个对象,那么这个对象就会永远丢失,这就是所谓的内存泄漏的一个典型例子--某个地方有一个对象,但却无法访问,它占用的内存也就丢失了,不能再使用了。可以这样想--你有一本书和一张借书卡。这本书在巨大的仓库中的某个地方,除非你知道去哪里找(用借书卡),否则你永远找不到它。因此,如果你丢失了所有的借书证副本,那么这本书对你来说就像丢失了一样--尽管它显然就在那里的某个地方。
发布于 2015-08-24 00:20:19
答案是,您创建的对象不会被删除,因为您已经在堆上创建了它们,但指针变量超出了作用域。解决方案是,将声明放在作用域之外,并在作用域中进行赋值:
string user_input;
getline(cin, user_input);
istringstream iss(user_input);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(vec));
Bureaucrat *bureaucrat;
Toolbox *toolbox;
Crescendo *crescendo;
Paperdoll *paperdoll;
Fistfullodollars *fistfullodollars;
for(int i=0; i<8; i++)
{
if(vec.at(i)=="Avalanche")
{
Avalanche *avalanche = new Avalanche(5);
std::unique_ptr<Avalanche> ptr(new Avalanche(5)); // even tried using unique pointer.
cout<<"Avalanche: "<<avalanche->c_game<<endl;
}
else if(vec.at(i)=="Bureaucrat")
{
bureaucrat = new Bureaucrat(5);
cout<<"Bureaucrat: "<<bureaucrat->c_game<<endl;
}
else if(vec.at(i)=="Toolbox")
{
toolbox = new Toolbox(5);
cout<<"Toolbox: "<<toolbox->c_game<<endl;
}
else if(vec.at(i)=="Crescendo")
{
crescendo = new Crescendo(5);
cout<<"Crescendo: "<<crescendo->c_game<<endl;
}
else if(vec.at(i)=="Paperdoll")
{
paperdoll = new Paperdoll(5);
cout<<"Paperdoll: "<<paperdoll->c_game<<endl;
}
else if(vec.at(i)=="FistfullODollars")
{
fistfullodollars = new Fistfullodollars(5);
cout<<"FistfullOdollars: "<<fistfullodollars->c_game<<endl;
}
}
cout<<ptr.c_game<<endl; // give an error not declared发布于 2015-08-24 00:21:05
ptr是在堆栈上声明的,它所指向的对象是delete绑定的。当if(vec.at(i)=="Avalanche") {}结束时,ptr (它是堆栈分配的)会超出作用域并且不再可访问。
https://stackoverflow.com/questions/32168727
复制相似问题