[英]Memory Management : Returning a vector element and deleting(pop_back) it
Here is a Template class I've made to catch up on templates 这是我为了赶上模板而制作的模板类
template <typename T>
class Myclass {
std::vector<T> v;
public:
Myclass(): v({0}){;}
Myclass(const Myclass& M)
{
this->v={1,2}; //ignore this I'm gonna use int for testing
}
~Myclass()
{
std::cout<<"Destructor";
}
void setter(T i)
{
v.push_back(i);
}
auto getter() -> decltype(T)
{
return v.back();
}
};
I would like to have the getter function return the last element in v
and pop_back()
. 我想让getter函数返回
v
和pop_back()
的最后一个元素。 Now I could store the back()
value in a variable and just pop_back()
. 现在我可以将
back()
值存储在变量中,只pop_back()
。 But I was hoping I could come up with smart pointers to do the same. 但是我希望我能拿出聪明的指针来做同样的事情。 Here's what I came up with
这就是我想出来的
auto getter() -> decltype(v.back())
{
std::unique_ptr<T> p1 (new T);
*p1=v.back();
v.pop_back();
return *p1;
}
and my main is 而我的主要是
Myclass<int> m1;
m1.setter(5);
Myclass<int> m2=m1;
std::cout<<m1.getter()<<m1.getter()<<std::endl;
std::cout<<m2.getter()<<m2.getter()<<m2.getter();
Yeah I want to do it with local smart pointers so that I can "be sure" of the objects destruction. 是的我想用本地智能指针做这件事,这样我就可以“确定”对象的破坏。 Now My program compiles but runs endless.
现在我的程序编译但运行无穷无尽。
No need for heap allocation, just use a good old local variable: 不需要堆分配,只需使用一个好的旧局部变量:
T getter()
{
T temp = std::move(v.back());
v.pop_back();
return temp;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.