I am editing some code of an open source game and normally the code doesn't directly access the player or creature class; however its parameter Cylinder is at the top of the food chain when it comes to everything.
My question is should I be deleting all these pointers or setting them to NULL after I am done with them?
Here is the code I've written; it works fine but I don't want to crash the server over an issue such as a dangling pointer (still a bit new to C++).
bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/)
{
if (cylinder == nullptr) {
return false;
}
if (money == 0) {
return true;
}
if (Creature *creature = cylinder->getCreature()) {
if (Player *player = creature->getPlayer()) {
uint64_t cash = player->getBankBalance();
if (cash < money) {
return false;
}
player->setBankBalance(cash - money);
}
}
return true;
}
void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/)
{
if (Creature *creature = cylinder->getCreature()) {
if (Player *player = creature->getPlayer()) {
player->setBankBalance(player->getBankBalance() + money);
}
}
}
In general (and unless the documentation says otherwise), don't delete objects if you are passed a pointer. Assume that you are not being given ownership of the object.
Modern C++ helps you avoid needing to know whether you are being given ownership: you may be given a std::shared_ptr<Cylinder> or a std::unique_ptr<Cylinder> - either way, deletion is handled for you when the smart pointer goes out of scope. But often, you have to work with a library that doesn't give you such reassurance.
There's no need to null out any pointers used within a small scope (e.g. a function). If you keep pointer variables around for longer (in a member variable, perhaps), then it may help prevent accidents if you do so. As C++ is not a garbage-collected language, there's no benefit from nulling pointers that are about to go out of scope.
delete is only required if there is a call to new when you obtain the Cylinder object from the game. There probably isn't, but you need to check the code.
Setting to NULL is something that you do if the object pointed to has been (or is at risk of getting) deleted. This is only to ensure that the invalid pointer cannot be accidentally used some time later.
Related
So, I have an array of a class called "Customer"
Customer** customersarray[] = new Customer*[customer];
I'm receiving int customer with cin.
anyways, in customer.cpp, there is a method called void deactivate().
which goes like this:
void Custmoer::deactivate()
{
if (this != NULL)
remove this;
//this = NULL; I want to do this but it doesn't work.
}
and the purpose of this is to remove it from customer array when satisfies a certain condition. So for example,
for (int i = customer - 1; i >= 0; i--)
{
if (customersarray[i]->getAngerLevel() == 5) {
customersarray[i]->deactivate();
}
for (int z = i; i < customer - 1; i++) {
*(customersarray + z) = *(customersarray + z + 1);
}
customer--;
}
so my first questions are:
why does this = NULL not work?
is there a simpler way to remove something from pointer array when a condition is satisfied? (for example, remove all customers that has anger level of 5.)
Your mistake is thinking that you can remove something from a Customer* array by some magic inside the Customer class, but that's not true. Just remove a customer from the customer array where ever the customer array is. For instance using remove_if
#include <algorithm>
Customer** customersarray = new Customer*[customer];
...
customer = std::remove_if(customersarray, customersarray + customer,
[](Customer* c) { return c->anger() == 5; }) - customersarray;
This updates the customer variable to be the new size of the array, but doesn't free or reallocate any memory. Since you are using dynamic arrays and pointers you are responsible for that.
Which is why you should really not be using pointers or arrays, but using vectors instead.
std::vector<Customer> customerVector;
Life will be so much simpler.
Type of "this" is a constant pointer which means you cant change where it points
Your function can return a boolean and if its true just set your pointer to null
You'll be much better off using a std::vector, all memory memory management gets much safer. You cannot modify the this pointer, but that would be meaningless anyway:
It is a local variable, so any other pointer outside would not be changed, not even the one you called the function on (x->f(): the value of x is copied into this).
It contains the address of the current object - the current object is at a specific memory location and cannot be moved away from (not to be mixed up with 'moving' in the context of move semantics!).
You can, however, delete the current object (but I don't say you should!!!):
class Customer
{
static std::vector<Customer*> customers;
public:
void commitSuicide()
{
auto i = customers.find(this);
if(i != customers.end())
customers.erase(i);
delete this;
}
}
Might look strange, but is legal. But it is dangerous as well. You need to be absolutely sure that you do not use the this pointer or any other poiner to the current object any more afterwards (accessing non-static members, calling non-static functions, etc), it would be undefined behaviour!
x->commitSuicide();
x->someFunction(); // invalid, undefined behaviour!!! (x is not alive any more)
Similar scenario:
class Customer
{
static std::vector<std::unique_ptr<Customer>> customers;
public:
void commitSuicide()
{
auto i = customers.find(this);
if(i != customers.end())
{
customers.erase(i); // even now, this is deleted!!! (smart pointer!)
this->someFunction(); // UNDEFINED BEHAVIOUR!
}
}
}
If handling it correctly, it works, sure. Your scenario might allow a much safer pattern, though:
class Customer
{
static std::vector<std::unique_ptr<Customer>> customers;
public:
Customer()
{
customers->push_back(this);
};
~Customer()
{
auto i = customers.find(this);
if(i != customers.end())
customers.erase(i);
}
}
There are numerous variations possible (some including smart pointers); which one is most appropriate depends on the use case, though...
First of all, attending to RAII idiom, you are trying to delete an object before using its destructor ~Customer(). You should try to improve the design of your Customer class through a smart use of constructor and destructor:
Customer() {// initialize resources}
~Customer() {// 'delete' resources previously created with 'new'}
void deactivate() {// other internal operations to be done before removing a customer}
Then, your constructor Customer() would initialize your internal class members and the destructor ~Customer() would release them if necessary, avoiding memory leaks.
The other question is, why do you not use another type of Standard Container as std::list<Customer>? It supports constant time removal of elements at any position:
std::list<Customer> customers
...
customers.remove_if([](Customer foo) { return foo.getAngerLevel() == 5; });
If you only expect to erase Customer instances once during the lifetime of the program the idea of using a std::vector<Customer> is also correct.
I am wondering how one would go about returning a new object from a C++ function. For example, I have a SQLite wrapper which used to mix in Objective-C and I modifying it to be purely C++.
So, for example:
list<char*> * SqliteWrapper::RunQuery(const char *query)
{
list<char*> * result = new list<char*>();
//Process query
return result;
}
the issue that I can see in this, is that who owns the object? The calling class or the class that created the object? What is worse, is that this is very prone to memory leaks. If the caller object does not delete the newly created object, the app will end up with a memory leak.
Now that I think about this, this would make a lot of sense:
int SqliteWrapper::RunQuery(const char *query, list<char*>& result)
{
//Process query
return errorCode;
}
Are there any other approaches to this? I have been a C# programmer for a while and only now am starting to work heavily with C/C++.
Many programmers do this:
If it is a pointer that is returned, I am being given the object's identity (it's location in memory is unique) I must manage that. I am responsible for deleting it.
(Pointer = my job)
references however let you pretend you are being passed the object, to look at and use. you are not responsible for deleting these, something else is.
BUT:
"Naked pointers" may be frowned upon for code like this (it's very subjective) so some would say use a "unique_ptr" to that, these can be moved, and delete what they point to when deleted (unless the stuff is moved out of them), by returning one and not using it, it will be deleted.
(tell me if you want me to flesh this out, see also "shared_ptr" if multiple things have a pointer, this will delete what it points to when the last shared_ptr pointing to it is deleted)
Addendum 1
unique_ptr<list<char*>> SqliteWrapper::RunQuery(const char *query)
{
list<char*> * result = new list<char*>();
//Process query
return make_unique<list<char*>>(result);
}
Remember you can only move, not copy unique_ptrs
Well. You are right.
First example would be a bad style, since in such a code is hardly readable and it is hard to track bugs in it.
Usually people use the second approach with reference.
In the same way you can use pointer, allocating the return object before function call.
Third approach would be to use class instead of function. It is convinient if your function does complicated process with many parameters. In this case you store result as a data member of the class and ownership is obvious:
class SqliteWrapper {
...
class ProcessQuery {
public:
ProcessQuery():fQ(0),fP1(0){}
SetQuery(const char *query){ fQ = query; }
SetP1(int p1){ fP1 = p1; }
...
list<char*> GetResult(){ return fR; } // copy
int Run();
private:
const char *fQ;
int fP1;
...
list<char*> fR;
}
...
}
int SqliteWrapper::Process::Run()
{
//Process query
return errorCode;
}
I wrote the following code creating singleton instance of my interface manager.
#include <intrin.h>
#pragma intrinsic(_ReadWriteBarrier)
boost::mutex global_interface_manager_creation_mutex;
interface_manager* global_interface_manager = NULL;
interface_manager* get_global_interface_manager() {
interface_manager* volatile temp = global_interface_manager;
_ReadWriteBarrier();
if (temp == NULL) {
boost::mutex::scoped_lock(global_interface_manager_creation_mutex);
temp = global_interface_manager;
if (temp == NULL) {
temp = new interface_manager();
_ReadWriteBarrier();
global_interface_manager = temp;
}
}
return temp;
}
But I don't want to use the lock and memory barrier so change the code to:
interface_manager* get_global_interface_manager() {
interface_manager* volatile temp = global_interface_manager;
__assume(temp != NULL);
if (temp == NULL) {
temp = new interface_manager();
if(NULL != ::InterlockedCompareExchangePointer((volatile PVOID *)&global_interface_manager, temp, NULL)) {
delete temp;
temp = global_interface_manager;
}
}
return temp;
}
It seems like this code works well but I don't be sure and I really don't know how to test it is correct.
My question would be: Is it really, really, really necessary to make a threadsafe singleton?
Singletons are debatable, but they do have their uses (and I guess discussing those would be going far off-topic).
However, threadsafe singletons are something that is 99.99% of the time unnecessary and 99.99% of the time implemented wrong, too (even people who should know how to do it right have proven in the past that they got it wrong). So, I think that in this case "do you really need this" is a valid concern.
If you create an instance of your singleton at application startup, for example from within main(), there will be only one thread. That can be as easy as calling get_global_interface_manager() once, or calling yourlibrary::init() which implicitly calls get().
Any concerns about thread-safety are irrelevant as soon as you do this, as there will be forcibly only one thread at this time. And, you are guaranteed that it will work. No ifs and whens.
A lot of, if not all, libraries require you to call an init function at startup, so that is not an uncommon requirement, either.
Have you looked into using pthread_once? http://sourceware.org/pthreads-win32/manual/pthread_once.html
This is the use case it was made for.
#include <stddef.h> // NULL
#include <pthread.h>
static pthread_once_t once_control = PTHREAD_ONCE_INIT;
static interface_manager* m;
static void* init_interface_manager()
{
m = new interface_manager;
return NULL;
}
interface_manager* get_global_interface_manager()
{
pthread_once(&once_control, &init_interface_manager);
return m;
}
One of the difficult parts of multi-threaded programming is that something might appear to work 99.9% of the time, then fail miserably.
In your case, there's nothing to prevent two threads from getting NULL back from the global pointer and both allocating new singletons. One will get deleted, but you'll still pass it back as the return value from the function.
I even had trouble convincing myself that my own analysis was correct.
You could fix it easily by returning global_interface_manager rather than temp. There's still the possibility of creating an interface_manager that you turn around and delete, but I assume that was your intention.
You could store the singleton as an atomic reference. After instantiating, CAS to set the reference. This will not guarantee that two copies don't get instantiated, only that the same one will always be returned from inst. Since standard C doesn't have atomic instructions I can show it in Java:
class Foo
{
static AtomicReference<Foo> foo = new AtomicReference<>();
public static Foo inst()
{
Foo atomic = foo.get();
if(atomic != null)
return atomic;
else
{
Foo newFoo = new Foo();
//newFoo will only be set if no other thread has set it
foo.compareAndSet(null, newFoo);
//if the above CAS failed, foo.get would be a different object
return foo.get();
}
}
}
I've been trying to use smart pointers to upgrade an existing app, and I'm trying to overcome a puzzle. In my app I have a cache of objects, for example lets call them books. Now this cache of books are requested by ID and if they're in the cache they are returned, if not the object is requested from an external system (slow operation) and added to the cache. Once in the cache many windows can be opened in the app, each of these windows can take a reference to the book. In the previous version of the app the programmer had to maintain AddRef and Release, when every window using the Book object was closed, the final Release (on the cache manager) would remove the object from the cache and delete the object.
You may have spotted the weak link in the chain here, it is of course the programmer remembering to call AddRef and Release. Now I have moved to smart pointers (boost::intrusive) I no longer have to worry about calling AddRef and Release. However this leads to a problem, the cache has a reference to the object, so when the final window is closed, the cache is not notified that no-one else is holding a reference.
My first thoughts were to periodically walk the cache and purge objects with a reference count of one. I didn't like this idea, as it was an Order N operation and didn't feel right. I have come up with a callback system, which is better but not fantastic. I have included the code for the callback system, however I was wondering if anyone had a better way of doing this?
class IContainer
{
public:
virtual void FinalReference(BaseObject *in_obj)=0;
};
class BaseObject
{
unsigned int m_ref;
public:
IContainer *m_container;
BaseObject() : m_ref(0),m_container(0)
{
}
void AddRef()
{
++m_ref;
}
void Release()
{
// if we only have one reference left and we have a container
if( 2 == m_ref && 0 != m_container )
{
m_container->FinalReference(this);
}
if( 0 == (--m_ref) )
{
delete this;
}
}
};
class Book : public BaseObject
{
char *m_name;
public:
Book()
{
m_name = new char[30];
sprintf_s(m_name,30,"%07d",rand());
}
~Book()
{
cout << "Deleting book : " << m_name;
delete [] m_name;
}
const char *Name()
{
return m_name;
}
};
class BookList : public IContainer
{
public:
set<BookIPtr> m_books;
void FinalReference(BaseObject *in_obj)
{
set<BookIPtr>::iterator it = m_books.find(BookIPtr((Book*)in_obj));
if( it != m_books.end() )
{
in_obj->m_container = 0;
m_books.erase( it );
}
}
};
namespace boost
{
inline void intrusive_ptr_add_ref(BaseObject *p)
{
// increment reference count of object *p
p->AddRef();
}
inline void intrusive_ptr_release(BaseObject *p)
{
// decrement reference count, and delete object when reference count reaches 0
p->Release();
}
} // namespace boost
Cheers
Rich
I never used boost::intrusive smart pointers, but if you would use shared_ptr smart pointers, you could use weak_ptr objects for your cache.
Those weak_ptr pointers do not count as a reference when the system decides to free their memory, but can be used to retrieve a shared_ptr as long as the object has not been deleted yet.
You can use boost shared_ptr. With this you can provide a custom deleter (see this SO thread on how to do it). And in that custom deleter you know that you have reached the last reference count. You can now remove the pointer from the cache.
You need to keep in your cache weak pointers instead of shared_ptr.
You might consider writing an intrusive_weak_ptr for your cache class. You will still need to do something to clean out the expired weak pointers in your cache from time to time, but it's not as critical as cleaning up the actual cached objects.
http://lists.boost.org/boost-users/2008/08/39563.php is an implementation that was posted to the boost mailing list. It isn't thread safe, but it might work for you.
I have developed an array based implementation of a hashTable with several stock names, symbols, prices, and the like. I need to remove a stock from my array. I am told that using the delete operator is bad object oriented design. What is the good object oriented design for deletion?
bool hash::remove(char const * const symbol, stock &s,
int& symbolHash, int& hashIndex, int& usedIndex)
{
symbolHash = this->hashStr( symbol ); // hash to try to reduce our search.
hashIndex = symbolHash % maxSize;
usedIndex = hashIndex;
if ( hashTable[hashIndex].symbol != NULL &&
strcmp( hashTable[hashIndex].symbol , symbol ) == 0 )
{
delete hashTable[hashIndex].symbol;
hashTable[hashIndex].symbol = NULL;
return true;
}
for ( int myInt = 0; myInt < maxSize; myInt++ )
{
++usedIndex %= maxSize;
if ( hashTable[usedIndex].symbol != NULL &&
strcmp( hashTable[usedIndex].symbol , symbol ) == 0 )
{
delete hashTable[usedIndex].symbol;
hashTable[usedIndex].symbol = NULL;
return true;
}
}
return false;
}
Noticing that i have a stock &s as a parameter, i can use it like this:
s = &hashTable[usedIndex];
delete s.symbol;
s.symbol = NULL;
hashTable[usedIndex] = &s;
This does work however, it results in a memory leaks. Even then, i am not sure if it is good object orinted design.
here is my header, where stock and all that stuff is initialized and defined.
//hash.h
private:
friend class stock;
int isAdded; // Will contain the added hash index.
// Test for empty tables.
// Can possibly make searches efficient.
stock *hashTable; // the hashtable will hold all the stocks in an array
};
// hashtable ctor
hash::hash(int capacity) : isAdded(0),
hashTable(new stock[capacity]) // allocate array with a fixed size
{
if ( capacity < 1 ) exit(-1);
maxSize = capacity;
// We can initialize our attributes for the stock
// to NULL, and test for that when searching.
for ( int index = 0; index < maxSize; index++ )
{
hashTable[index].name = NULL;
hashTable[index].sharePrice = NULL;
hashTable[index].symbol = NULL;
}
}
// stock.h
...
friend class hashmap;
private:
const static int maxSize; // holds the capacity of the hash table minus one
date priceDate; // Object for the date class. Holds its attributes.
char *symbol;
char *name;
int sharePrice;
};
My question is still just, how do i preform a safe remove?
s = &hashTable[usedIndex];
delete s.symbol;
s.symbol = NULL;
hashTable[usedIndex] = &s;
That seems to work, but results in memory leaks! How is this done safely?
delete hashTable[usedIndex].symbol;
hashTable[usedIndex].symbol = NULL; <-- without doing this.
The status of the slot in the array (empty, etc) should not be recorded in the stock instance. That's bad object oriented design. Instead, I need to store the status of an array slot in the array slot itself.
How would i do that?
NOTE: This answer is just addressing
some of the things you are doing
incorrectly. This is not the best way
to do what you are doing. An array of
stock** would make more sense.
Doesn't your stock class have a constructor? You don't need to know anything about the stock class if it is a proper object:
hash::hash(int capacity) // change this to unsigned and then you can't have capacity < 0
: isAdded(0)
, hashTable(0) // don't call new here with bad parameters
{
if ( capacity < 1 ) exit(-1); // this should throw something, maybe bad_alloc
maxSize = capacity;
hashTable = new stock[capacity]; // this calls the stock() constructor
// constructor already called. All this code is useless
// We can initialize our attributes for the stock
// to NULL, and test for that when searching.
// for ( int index = 0; index < maxSize; index++ )
// {
// hashTable[index].name = NULL;
// hashTable[index].sharePrice = NULL;
// hashTable[index].symbol = NULL;
// }
}
class stock {
char* name; // these should be std::string as it will save you many headaches
char* sharePrice; // but I'll do it your way here so you can see how to
char* symbol; // avoid memory leaks
public:
stock() : name(0), sharePrice(0), symbol(0) {}
~stock() { delete[] name; delete[] sharePrice; delete[] symbol; }
setName(const char* n) { name = new char[strlen(n)+1]; strcpy(name, n); }
setPrice(const char* p) { sharePrice = new char[strlen(p)+1]; strcpy(sharePrice, p); }
setSymbol(const char* s) { symbol = new char[strlen(s)+1]; strcpy(symbol, n); }
const char* getName() const { return name; }
const char* getPrice() const { return sharePrice; }
const char* getSymbol() const { return symbol; }
}
To get good object oriented design, a collection should be agnostic of what is stored in it. This really has nothing to do with using the delete operator per se, but requiring an object (your stock in this case) to store data structure specific code is.
There are two plans things I can see to quickly fix this issue.
Use an array of stock * instead of just stock. Then a null value will mean the slot is open, and a non-null value will mean the slot can be used. In this plan you would call new and delete on the entire stock object as it is inserted and then as it is removed, which is more object oriented than just the symbol.
Create a HashSlot class that wraps the stock item, adding the book keeping values that are needed.
Your hash table would then be an array of HashSlot items.
I prefer the second. In either case, stock should have a destructor that clears up its own internal memory.
It looks like you're using (or trying to use) open addressing with linear-probing for collision resolution. In that case, you need to somehow mark items as deleted (as opposed to empty), so that you can still access items which fall after deleted items. Otherwise, you won't be able to lookup certain items because your probing sequence will be terminated prematurely if it finds a deleted bucket. Therefore, you won't be able to access certain items in the table anymore and that's probably why you're getting a memory leak.
Basically, you're supposed to start at the hash index, compare the item with your key, and then if it isn't equal to your key, increment to the next index and repeat until either you find the item, or until you encounter an empty bucket. If you find the item, delete the item and mark that index as deleted. But the important thing is that you have some way to distinguish between an empty hash bucket, and a deleted hash bucket, otherwise a deleted bucket will cause you to terminate your probing sequence early.
As for "good object oriented design", there is no inherent property of object-oriented programming that necessarily makes using delete a bad design. Every data structure that allocates memory has to free it somehow. What you're probably referring to is the fact that it's usually safer and less work to implement classes that don't manage their own memory, but rather delegate that responsibility to pre-made container classes, like std::vector or std::string
I have developed an array based implementation of a hashTable with several stock names, symbols, prices, and the like. I need to remove a stock from my array. I am told that using the delete operator is bad object oriented design. What is the good object oriented design for deletion?
Well, one of the key principles behind object oriented design is reusability.
Hence, the only good object oriented design is to reuse the solutions that have already been developed for you!
C++ comes with a perfecetly good map class. Most recent compilers also support TR1, which adds a hash table under the name unordered_map.
The Boost libraries also contain an implementations of unordered_map in case you're stuck on a compiler without TR1 support.
As for your question about delete:
I'm not sure who told you that delete is "bad object-oriented design", or why, but what they might have meant is that it is bad C++ design.
A common guideline is that you should never explicitly call delete. Instead, it should be called implicitly through the use of the RAII idiom.
Whenever you create a resource that must, at some later point, be deleted, you wrap it in a small stack-allocated object, whose destructor calls delete for you.
This guarantees that it gets deleted when the RAII object goes out of scope, regardless of how you leave the scope. Even if an exception is thrown, the object still gets cleaned up, its destructor called, and your resource deleted. If you need more complex ways to manage the object's lifetime, you might want to use smart pointers, or just extend your RAII wrapper with copy constructor and assignment operator to allow ownership of the resource to be copied or moved.
That is good C++ practice, but has nothing to do with object-oriented design. Not everything does. OOP isn't the holy grail of programming, and not everything has to be OOP. Good design is much more important than good OOP.