Guy*_*ean 6 c++ scope memory-management
我常常想知道,
我知道我可以使用new关键字将同一个指针作为参数传递给函数,同时创建一个指向对象实例的指针.就像我在下面Animation::newFrame的例子中给出的功能一样.
但是,我也知道,作为一般规则,我负责调用delete我创建的东西new.
所以当我像这样调用Frame的构造函数时:
Frame* myFrame
= new Frame(new point(0,0), new point(100,100), new point(50,20));
Run Code Online (Sandbox Code Playgroud)
对于我new在上面的函数调用中创建的3个点最终释放内存的责任在哪里?
毕竟,以上3个新点并没有让我可以打电话的名字delete.
我总是假设它们属于它们被调用的函数的范围,并且它们将简单地超出函数的范围.然而,最近我一直在想也许不是这样.
我希望我在这里已经足够清楚了.
提前致谢,
家伙
struct Frame
{
public:
point f_loc;
point f_dim;
point f_anchor;
//the main constructor:: Creates a frame with some specified values
Frame(point* loc, point* dim, point* anchor)
{
f_loc = loc;
f_dim = dim;
f_anchor = anchor;
}
};
struct Animation
{
public:
vector<Frame*> frameList;
//currFrame will always be >0 so we subtract 1
void Animation::newFrame(int &currFrame)
{
vector<Frame*>::iterator it;//create a new iterator
it = frameList.begin()+((int)currFrame);//that new iterator is
//add in a default frame after the current frame
frameList.insert(
it,
new Frame(
new point(0,0),
new point(100,100),
new point(50,20)));
currFrame++;//we are now working on the new Frame
}
//The default constructor for animation.
//Will create a new instance with a single empty frame
Animation(int &currFrame)
{
frameList.push_back(new Frame(
new point(0,0),
new point(0,0),
new point(0,0)));
currFrame = 1;
}
};
Run Code Online (Sandbox Code Playgroud)
编辑:我忘了提到这个问题纯粹是理论上的.我知道有更好的替代原始指针,如智能指针.我只想加深对常规指针的理解以及如何管理它们.
上面的示例也取自我的一个项目,实际上是C++/cli和c ++混合(托管和非托管类),这就是为什么构造point*函数只接受而不是通过value(point)传递.因为point是非托管结构,因此在托管代码中使用时,必须由我自己,程序员管理.:)
Joh*_*ing 11
澄清并且经常强制执行资源所有权的语义是程序员的责任.这可能是一件棘手的事情,尤其是当您在这里处理原始指针时,在资源所有权尚未给予任何实际设计考虑的环境中.后者不仅在新手程序员编写的玩具程序中很普遍,而且在具有数十年经验并且应该更熟悉的人所编写的生产系统中很普遍.
在上面的实际情况中,Frame对象本身必须负责delete传入的3个指针,并且无论构造什么Frame本身都必须负责delete.
由于资源所有权是一个雷区,程序员很久以前发明了许多技术来澄清所有权的语义,并使粗略的程序员引入错误和泄漏变得更加困难.现在,在C++中,它被认为是避免原始指针的最佳实践,事实上,只要有可能,就会完全动态分配 - 主要是因为资源所有权是如此危险的雷区.
在C++中,用于实现这些目标的主要成语是RAII和所用的主要工具是auto_ptr(C++ 03), unique_ptr,shared_ptr和它们的同类.Boost还提供了许多所谓的"智能指针".其中许多与C++ 11中发现的并行(事实上,C++ 11中的新智能指针最初是由Boost开发的),但也有一些超越了,例如intrusive_ptr.