简体   繁体   English

混合指向已分配对象和作用域对象的指针

[英]Mixing pointers to allocated objects and scoped objects

What if I have a map that points to objects that are supposed to be allocated, but some other caller inserts a pointer to an object that will go out of scope? 如果我有一个映射指向应该分配的对象,但是其他一些调用者插入了一个将超出范围的对象的指针,该怎么办? Considering you can add object pointers in two ways: 考虑到您可以通过两种方式添加对象指针:

class MyClass {
    public:
        std::map<int, MyObject*> myMap;
        MyClass();
        ~MyClass();
};
MyClass::MyClass(){}
MyClass::~MyClass(){
    std::map<int, MyObject*>::iterator it;
    for(it = this->myMap.begin(); it != this->myMap.end(); it++){
        delete it->second;
    }
}

Case 1 - by reference for objects that will go out of scope 情况1-通过引用将超出范围的对象

MyObject myObject;
ptrMyClass->myMap.insert(std::make_pair(0, &myObject));

Case 2 - by allocated objects 情况2-按分配的对象

MyObject myObject = new MyObject();
ptrMyClass->myMap.insert(std::make_pair(0, myObject));

Is it sensible to do this? 这样做明智吗?

for(it = this->myMap.begin(); it != this->myMap.end(); it++){
     if(sizeof(it->second) == sizeof(MyObject)){
         delete it->second;
     }
 }

It will at least avoid a memory free error, and if I clear at the end, does it cover all cases? 这样至少可以避免出现无内存错误,如果我最后清除了,是否可以涵盖所有情况? Is it possible to avoid this situation in the first place? 首先可以避免这种情况吗? (I use C++98) (我使用C ++ 98)

First of all this code: 首先此代码:

if(sizeof(it->second) == sizeof(MyObject)){

is equal to this: 等于这个:

if(sizeof(MyObject*) == sizeof(MyObject)){ 

so you either would not delete any, or if size of your object suddenly equal to a pointer you delete them all. 因此,您将不会删除任何对象,或者如果对象的大小突然等于指针,则将其全部删除。 In C++ there is no way by having only a pointer to determine if object is allocated dynamically or not. 在C ++中,无法仅通过一个指针来确定对象是否动态分配。 So you basically have 2 options: 因此,您基本上有2个选择:

1 Always own objects - when you have automatic aka scoped objects make a dynamically allocated copy.

2 Store additional information if you own the object or not, you can do that either by smart pointers or storing a flag together with pointer.

The solution would be smart pointers. 解决方案将是智能指针。 Since you use C++98, I've included a possible implementation. 由于您使用的是C ++ 98,因此我提供了一种可能的实现。

template <typename t>
class auto_ptr
{
  private:
    t *_ptr;

  public:
    auto_ptr(t *ptr) : _ptr(ptr){};

    auto_ptr(auto_ptr<t> &lhs) : _ptr(lhs._ptr)
    {
        lhs._ptr = NULL;
    };

    ~auto_ptr()
    {
        if (_ptr != NULL)
        {
            delete _ptr;
        }
    };

    auto_ptr<t> &operator=(auto_ptr<t> &lhs)
    {
        _ptr = lhs._ptr;
        lhs._ptr = NULL;
        return *this;
    };

    t *get()
    {
        return _ptr;
    };
};

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

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