简体   繁体   English

C ++中的原始指针

[英]Raw Pointer in C++

I have a piece of C++ classes and I have the raw pointer to the objects. 我有一个C ++类,并且有指向对象的原始指针。 The pointer to the object would get passed down to the function. 指向对象的指针将传递给该函数。 The problem is the underlying function might need to store the pointer at times in an STL container in which pointer to the object would be used later on. 问题是底层函数可能需要有时将指针存储在STL容器中,以后将在其中使用指向对象的指针。 If I am not using shared_ptr, I am thinking of adding a bool flag to the class which indicates whether the caller of the function is responsible for deleting the object memory. 如果我没有使用shared_ptr,我正在考虑向该类添加一个bool标志,该标志指示该函数的调用者是否负责删除对象内存。 Would that be fine? 可以吗

Thanks. 谢谢。

Messy. 凌乱。 And rife with many potential bugs that will keep you at work well past midnight on a Saturday. 而且还有很多潜在的错误,这些错误将使您在星期六的午夜过后仍然可以正常工作。

Be clear and consistent about resource ownership. 对资源所有权要保持清楚和一致。 Either the vector owns the pointers, or some specific function owns the pointers, or smart pointers own pointers. 向量要么拥有指针,要么某个特定的函数拥有指针,或者智能指针拥有指针。 Any mixing of these semantics will have the ultimate result of you tearing your hair out late at night. 这些语义上的任何混合,最终都会导致您在深夜时把头发扯掉。

The best solution is usually to use a reference-counted smart pointer. 最好的解决方案通常是使用引用计数的智能指针。 (As you probably already know all to well, you can't use std::auto_ptr ) Barring that, create a class whose sole purpose in life is to allocate, deallocate and grant access to the vector's contained pointers. (您可能已经很清楚了,您不能使用std::auto_ptr )除非如此,否则请创建一个类,其唯一的目的是分配,释放和授予对向量的包含指针的访问权限。 Any function that needs the contained object would go through your manager class to get to them. 需要包含对象的任何函数都将通过您的经理类来访问它们。

STL containers will almost certainly take a copy of the object which you insert into it. STL容器几乎可以肯定会复制您插入到其中的对象的副本。 When the object is removed from the container, the object will be destroyed. 从容器中取出对象时,该对象将被破坏。

If the default copy constructor is not sufficient (ie you need to do a deep copy of the object), you need to ensure you implement your own version which does the copy properly. 如果默认的复制构造函数不足(即,您需要对对象进行深层复制),则需要确保实现自己的版本,该版本可以正确执行复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM