简体   繁体   中英

exception proof assignment operator in c++

Below is an exception proof approach of assignment operator shared by Scott Meyer. Can anybody let me know that is it safe to delete the raw pointer?

int *orig =m_p; 
m_p=new int (*obj.m_p);
delete orig;

The problem with the question is that you can't tell what m_p contains initially. If its value has been obtained by some &intVar , then the answer is: NO. If the value has been produced by new but has already been delete d and not set to NULL, then the answer is NO again. If the value is undefined, the answer is another NO.

That leaves a possibilitity where it is safe.

If you cannot do without a raw pointer

Yes you have to delete it and it is safe. You can do one more thing, which is setting it to 0 after deleting it because Setting them to 0 after deleting is a good practice, except in destructors (because the object instance that contains the pointers is going away anyway). The standard allows deletes of NULL pointers (it does nothing), and any good OS with memory management will cause your program to crash on the first dereference (read or write) of a NULL pointer. So now it's up to your requirements that how you go for it

If you can do without a raw pointer

Raw pointer is not recommended to be used, there are other alternatives which you could go for like you can Use a managed pointer class instead of raw pointers. std::auto_ptr<>, boost::scoped_ptr<>, boost::shared_ptr<>, boost::weak_ptr<>, boost::intrusive_ptr<>, std::unique_ptr<> (C++0x). Even on multi-million line projects with tons of memory allocation this is used and even they need to very rarely do delete anything; all the pointers are managed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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