When you delete a pointer, you should set it to NULL, right?
Joe
Apr 10 '06
51 10461
Joe Van Dyk wrote: Object B gets deleted. It is (and out of my control) deleting the Object A pointer. It's not setting the Object A pointer to NULL.
It probably can't. Unless the function taking the pointer requires a
pointer to pointer or a reference to a pointer then it can only set its
own copy of the pointer to 0. Pointers are just values that contain
number representing addresses in memory. If you pass a pointer by
value you can't exactly effect anything by setting that value to 0 on
the other side...the original copy of the pointer is unchanged.
So, whether or not Object B is setting the pointer to 0 is an unknown
at this time and it doesn't really matter. You need to keep in mind
that B is apparently taking ownership of the pointer it is passed and
act accordingly, by possibly copying the object and passing the copy or
some other solution that makes sense to your problem.
Joe Van Dyk wrote: I'mÂ*notÂ*terri blyÂ*smart,Â*yo uÂ*see.
Why aren't you using a smart pointer? Then they can do the thinking for you.
(Roughly..;)
--
Phlip http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
"Joe Van Dyk" <jo********@boe ing.com> wrote in message
news:Ix******** @news.boeing.co m... When you delete a pointer, you should set it to NULL, right?
Joe
I'm a little surprised at the responses you've been getting from some very
experienced programmers. While a smart pointer might be the best solution
for your particular problem it doesn't answer your question.
I think the correct answer to your question should be: if you intend to
check the value of the pointer later on you should set it to NULL, otherwise
it doesn't matter. Some programs use the actual value of a pointer as a flag
whether it is pointing to something that needs to be deallocated. In those
cases you should null it when deleting. However, nothing in standard C++
depends on the value of a pointer after calling delete on it.
Also keep in mind that calling delete on a null value is a noop so you don't
need code like this:
if (ptr != 0)
delete ptr; // null-check not needed
Which allows you to write code like this (no endorsements made):
Foo *foo = 0;
:
:
if (allocFoo)
foo = new Foo;
:
:
if (deleteFoo)
{
delete foo;
foo = 0;
}
:
:
delete foo;
The code above is not that likely to occur as shown but inside
constructor/destructor code you might encounter this sequence of events.
Andrew
Victor Bazarov wrote: Joe Van Dyk wrote:
[..] Let's see if I can explain what's going on...
I've got an object (Object A) that contains two pointers to objects that Object A didn't create.
So something like
class Other; class A { Other *not_mine_1, *not_mine_2; public: ~A() {} // do nothing to pointers };
There's another object in the system, Object B. Object B has a function that requires an Object A pointer.
class B { public: void foo(A* aptr);
private:
A* aptr_; };
Object B gets deleted. It is (and out of my control) deleting the Object A pointer.
Which A pointer? You didn't say that B _owned_ a dynamic A object.
void B::foo(A* aptr)
{
aptr_ = aptr;
}
B::~B()
{
delete aptr_;
} It's not setting the Object A pointer to NULL.
Shouldn't be a problem _even_if_ the B actually owned that A and had a pointer to that dynamic object.
Now, there's threads involved here, so that may be complicating things... but I was curious as to if the Object A pointer should be set to NULL when Object B deletes it.
Well, no. Your problem is most likely is elsewhere. Read about "The Rule of Three" and follow it (concerning the B class). Also, make sure you're not deleting that B object _twice_ somewhere.
V
Yes, it's entirely possible the problem is elsewhere. I was just
wondering if it was something silly I was doing.
Joe
Phlip wrote: Joe Van Dyk wrote:
I'm not terribly smart, you see.
Why aren't you using a smart pointer? Then they can do the thinking for you. (Roughly..;)
Because I need to pass a raw Object A pointer to Object's B function. I
(as of now) can't change the code of class B to use smart pointers. I
don't think a smart pointer can help me there...
andrew queisser wrote: I'm a little surprised at the responses you've been getting from some very experienced programmers.
Some of us know the textbook answer (set the friggin' pointer to NULL),
while some of us can't remember the last time we actually did that. There's
more reasons than smart pointers.
Another alternative is to set the pointer equal to the address of a static
NullObject. Consider this code:
p = getPointerFromW hatever();
if (p)
p->method(42);
Using NullObjects, that becomes this:
p = getPointerFromW hatever();
assert(p);
p->method(42);
The code is one tick simpler; it has one less 'if' statement.
Replacing conditional statements with the interactions of virtual methods is
what OO is all about.
I think the correct answer to your question should be: if you intend to check the value of the pointer later on you should set it to NULL
Even if you don't intend to, if that pointer has remaining scope, set it to
NULL to make sure (on common implementations ) you get a clean crash and not
memory corruption if you then accidentally try to dereference the pointer.
--
Phlip http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Phlip wrote: Another alternative is to set the pointer equal to the address of a static NullObject. Consider this code:
p = getPointerFromW hatever(); if (p) p->method(42);
Using NullObjects, that becomes this:
p = getPointerFromW hatever(); assert(p); p->method(42);
The code is one tick simpler; it has one less 'if' statement.
Really? What is that assert doing there then?
What type does this static NullObject have?
Noah Roberts wrote: p = getPointerFromW hatever(); assert(p); p->method(42);
The code is one tick simpler; it has one less 'if' statement. Really? What is that assert doing there then?
It is not increasing the mental burden of reading the function. And we could
migrate it inside a new function, getReferenceFro mWhatever(), and this
function would be even shorter.
What type does this static NullObject have?
A type derived from Whatever class type that p points to, with
Whatever::metho d(int) overriden as a no-op.
--
Phlip http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Phlip wrote: Noah Roberts wrote:
p = getPointerFromW hatever(); assert(p); p->method(42);
The code is one tick simpler; it has one less 'if' statement. Really? What is that assert doing there then?
It is not increasing the mental burden of reading the function. And we could migrate it inside a new function, getReferenceFro mWhatever(), and this function would be even shorter.
That statement just makes no sense. I can't parse it and it doesn't
seem to apply to the question at all. What type does this static NullObject have?
A type derived from Whatever class type that p points to, with Whatever::metho d(int) overriden as a no-op.
That requires three things:
1) a special "NullObject " class for each and every class that could
have a pointer to it.
2) a special "NullObject " static for each of the above implementations .
3) that all classes and all member functions are polymorphic!!
Consider also functions that return values...they cannot be noops!
Now #2 is only by consequence of your initial requirements... it isn't
actually required to be static but could simply be constructed. This
results in more small objects than a static though.
#3 is the real killer.
I don't think you have thought this through quite enough yet though.
Null *pointer* object is viable. Dereference would throw an exception
or pop an assert. This of course requires the use of some form of
smart pointer...which has already been suggested.
I don't see a good implementation brewing out of your NullObject
though.
Noah Roberts wrote: >> p = getPointerFromW hatever(); >> assert(p); >> p->method(42); >> >> The code is one tick simpler; it has one less 'if' statement. > > Really? What is that assert doing there then?
The function is less complex. It formerly had a visible controlled
statement.
> What type does this static NullObject have? A type derived from Whatever class type that p points to, with Whatever::metho d(int) overriden as a no-op.
That requires three things:
1) a special "NullObject " class for each and every class that could have a pointer to it. 2) a special "NullObject " static for each of the above implementations . 3) that all classes and all member functions are polymorphic!!
Consider also functions that return values...they cannot be noops!
It also requires me to say, "Noah, I want you to find every pointer in your
program, and accomodate its pointee to have a potential NullObject _with_ a
no-op for every method."
Don't tempt me to. Instead, I will say this: http://www.industriallogic.com/xp/re...ullObject.html
Now notice that is a _refactor_. It's not a Design Pattern, or even a
universally perfect goal. It's a path of improvement, away from redundant
'if' statements to check pointers.
The ideal situation has no 'if' statements, no pointers, and no need for
NullObjects.
Now #2 is only by consequence of your initial requirements... it isn't actually required to be static but could simply be constructed. This results in more small objects than a static though.
Yes, of course its storage class could be different than static. If the
pointer were smart, maybe another 'new' would work.
Because my NullObjects have no state, they can be static.
#3 is the real killer.
You made 3 up.
I don't think you have thought this through quite enough yet though.
Noope. I have indeed not thought thru all the things you will make up. ;-)
--
Phlip http://www.greencheese.org/ZeekLand <-- NOT a blog!!! This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Asfand Yar Qazi |
last post by:
Hello. Partly for learning purposes, I have written a smart pointer class.
Could you please tell me what's wrong with it? (I know there's
something wrong with it, but just not what!)
Note that, as well as reference counting the stored pointer, it also has
the ability to be declared for incomplete types (I think). I.e.:
struct Incomplete;
|
by: nifsmith |
last post by:
Hi
I am creating my own Queue class to learn about Queues and pointers.
I have come across a question of two styles and I don't know if there
are any dangers associated with them.
I coded my remove function as follows
template <class T>
|
by: Songling |
last post by:
Hi gurus,
Just learnt from my co-worker that it's safe to delete a null pointer. I
tried it on sun box
(and linux), nothing bad happens. So it seems to be true. But does it apply
to all platforms?
Also if I delete a pointer twice, and don't nullify the pointer after the
first delete, it's going
to trap. If I do the nullify, no trap. Does it just confirm that it's safe
|
by: Venn Syii |
last post by:
I've searched all the forums but cannot find an answer to this question.
I do the following:
vector<MyClass*> myClassList;
Later in the program I try to add to myClassList with a .push_back(...)
I get an "out of memory" runtime error. I know I'm not out of memory
because normal vectors such as vector<int> a, still work, and still work
fine.
|
by: John Ratliff |
last post by:
When I dereference a pointer, does it make a copy of the object?
Say I had a singleton, and wanted an static method to retrieve it from
the class.
class foo {
private:
static foo *bar;
foo() {} // no public creation!
| |
by: KWienhold |
last post by:
I'm currently working on a project in C# (VS 2003 SP1, .Net 1.1) that
utilizes IStream/IStorage COM-Elements.
Up to now I have gotten everything to work to my satisfaction, but now
I have come across a problem I can't really explain:
When deleting an object from an IStorage, the space it used up will not
be freed, but rather marked as unused and overwritten the next time you
add an object to the storage.
This is obviously working as...
|
by: Jess |
last post by:
Hello,
I tried a program as follows:
include<iostream>
using namespace std;
class A{
public:
|
by: ma740988 |
last post by:
Given the snippet.
class foo {
public:
~foo() {
// type id should be able to get the type of the class ( I think )
std::cout << " foo destructing " << std::endl;
}
};
|
by: Rahul |
last post by:
Please read the following code
class Test{
public:
void * operator new (size_t t)
{ return malloc(t); }
void operator delete (void *p)
{ free(p); }
};
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |