简体   繁体   English

C ++指向对象的麻烦

[英]C++ trouble with pointers to objects

I have a class with a vector of pointers to objects. 我有一类带有指向对象的指针的向量。 I've introduced some elements on this vector, and on my main file I've managed to print them and add others with no problems. 我已经在此vector上引入了一些元素,并且在我的主文件中,我设法打印了它们并添加了没有问题的其他元素。 Now I'm trying to remove an element from that vector and check to see if it's not NULL but it is not working. 现在,我正在尝试从该向量中删除一个元素,并检查它是否不是NULL但不起作用。

I'm filling it with on class Test: 我在课堂上用Test填充它:

Other *a = new Other(1,1);
Other *b = new Other(2,2);
Other *c = new Other(3,3);

v->push_back(a);
v->push_back(b);
v->push_back(c);

And on my main file I have: 在我的主文件中,我有:

Test t;
(...)

Other *pointer = t.vect->at(0);

delete t.vect->at(0);
t.vect->erase(t.vect->begin());

if (pointer == NULL) { cout << "Nothing here.."; } // Never enters here..

Deleting a pointer doesn't have to zero it, it just frees the memory assigned there. 删除指针不必将其归零,它只是释放在那里分配的内存。 Using pointer is undefined after the delete though, as the memory is free to be used for other things. 但是,删除后仍未定义使用pointer ,因为该内存可自由用于其他用途。 Technically the C++ spec intentionally leaves it up to implementations whether they want to zero a deleted pointer or not, but practically none that I know of do so 从技术上讲,C ++规范有意将其留给实现,无论他们是否希望将已删除的指针归零,但实际上我所知没有这样做

删除指针所指向的内存不会将指针设置为NULL。

You set pointer equal to the address of something, and never touched it again, so of course it won't be null. 您将指针设置为等于某物的地址,并且再也没有碰过它,因此它当然不会为空。 The fact that you then did something to the object is irrelevant. 然后您对对象执行了某些操作这一事实是无关紧要的。

Using simple pointers, there is no safe way for pointer to determine whether the object it once pointed to has been deleted. 使用简单的指针,指针没有安全的方法来确定它曾经指向的对象是否已被删除。 The simplest way to do what you seem to want to do is by leaving it to the containers: if you're interested in that object, search for pointer in the vector to see whether it's still there (and don't delete the object without erasing the corresponding element from the vector, or you'll have the same problem all over again). 做您想做的事情的最简单方法是将其留给容器:如果您对该对象感兴趣,请在向量中搜索指针以查看其是否仍然存在(并且不要删除没有该对象的对象)从向量中删除相应的元素,否则您将再次遇到相同的问题)。

To overcome the checking a deleted ptr problem you could use boost::shared_ptr . 为了克服检查删除的ptr问题,您可以使用boost :: shared_ptr

Instead of delete use .reset() and to check if the ptr is still valid use .get() 而不是删除使用.reset()并检查ptr是否仍然有效,请使用.get()
(Actually you can just use if(p) where p is the shared_ptr because it has a conversion to bool) (实际上,您可以只使用if(p) ,其中p是shared_ptr,因为它可以转换为bool)

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

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