I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do
Obj *obj = libname_newDevice();
Now, should I use delete or should I do obj->deleteMe();? I ask because I am not exactly doing new so I shouldn't be doing the delete?
I have obj->create(theType); which returns a class with the Obj interface.
My real question is do I need a libname_deleteDevice(); or is obj->deleteMe() fine since I have a deleteMe in the interface?
Since you are abstracting the creation inside libname_newDevice() (which I have to say isn't a good approach), you should destroy using something like libname_destroyDevice (obj).
And as the comment from Martin suggests, it's best to put them in the constructor and destructor of a custom class, that you just need to create on stack, and the compiler will take care of the rest.
Please try to clarify your question. It's totally unclear to me.
Why do you speak of a graphical back end? Is it relevant to the question?
Are you asking how you should design your library or how you should use it?
It's good practice to have an object factory to create the object. I assume this is the role of libname_newDevice().
The library should also provide a way to delete the object (such as obj->DeleteMe() or libname_Delete(obj) ).
Don't rely on C++'s delete: caller and library might have been compiled with different version of the compiler, which would do different things regarding memory and resources allocation. It's therefore safer if your lib deletes the object it created.
I would take one step further.
If you are using a factory function to create, it may be logical to use a factory function to destroy. In addition to this to make it all nice and exetion safe wrap in in an object.
class ObjWrap
{
public:
ObjWrap()
:obj(libname_newDevice())
{}
~ObjWrap()
{ libname_deleteDevice(obj);}
private:
ObjWrap(ObjWrap const&); // Dont copy
void operator=(ObjWrap const&); // Dont copy
Obj* obj;
}; // If you want to copy then you need to extra work on ref counting
// This may need some form of smart pointer.
I think the best way would be to honor RAII and have some reference counting wrapper object (you can even use shared_ptr with a custom deallocator).
You definitely don't want to implement Obj::deleteMe(). It would have to do something like:
delete this;
while you were still inside this->deleteMe(). Follow Jaywalker's suggestion and make the destroy function take an Obj* as a parameter.
Related
I have a class called Widget. This class is abstract and has virtual methods. To avoid object slicing all Widgets are stored as references or pointers. I have several classes with constructors that store internally the widget given to them; thus the Widget stored must have been initialized outside the constructor and cannot be destroyed before the object is, therefore usually the Widget is allocated via dynamic memory. My question is regarding how to handle this dynamic memory; I have compiled a list of options (feel free to suggest others.) Which is the most idiomatic?
1. Smart pointers. Smart pointers seem like the right choice, but since I'm using C++98 I have to write my own. I also think that writing smart_pointer<Widget> all the time is a little ugly.
2. Copy Widgets when stored. Another course of action is to store a copy of the passed-in Widget instead of the original. This might cause object-slicing, but I'm not sure. Also, users might want to write classes themselves that store passed-in Widgets, and I wouldn't want to make it too complicated.
3. Let the user handle everything. I could perhaps make the user make sure that the Widget is deleted on time. This seems to be what Qt does (?). However, this again complicates things for the user.
I personally like this approach (it is not always applicable, but I used it successfully multiple times):
class WidgetOwner
{
vector<Widget*> m_data;
public:
RegisterWidget(Widget *p) { m_data.push_back(p); }
~WidgetOwner() { for (auto &p : m_data) delete p; }
};
This simple class just stores pointers. This class can store any derivatives of Widget provided that Widget has virtual destructor. For a polymorphic class this should not be a problem.
Note that once Widget is registered, it cannot be destroyed unless everything is destroyed.
The advantage of this approach is that you can pass around pointers freely. They all will be valid until the storage will be destroyed. This is sort of hand made pool.
Which is the most idiomatic?
The most idiomatic would certainly be what next versions of c++ decided to be "the way to go", and that would be smart pointers (You can find/use an implementation on boost for example, also other ones on the internet might be simpler for inspiration).
You can also decide that since you are using c++98 (that's a huge factor to take into consideration), you take what's idiomatic for that context, and since that was pretty much no man's land, the answer is most likely whatever home made design is the most appealing to you.
I think smart pointer is best choice. And if you feel template is ugly, try the typedef
I read other questions trying to figure this out but I didn't find much like what I have in mind. I'm kinda new to C++ and I just don't want to have my C++ code to look like "C with classes", or in other words, if there is a good "C++ way of doing this", that's what I'm looking for, but I'm a bit confused. Well, to the problem.
I have a class, say MyClass. Now, in other class, say MyContainer, I have a vector<MyClass> vec.
Let's say I'm now creating a method that populates a MyClass object with any arbitrary stuff and then pushes it into vec. First question is: should I allocate and push the object like the following? (using vector<MyClass> vec)
MyClass *obj = new MyClass(args);
vec.push_back(*obj);
I am not sure this is right, but by my understanding, this could make me avoid having to manually delete every instance of MyClass I put into vec when the instance of MyContainer is of no use anymore.
What bugs me is that, like I said, this does not seem right anyway, and the other way I can figure out is declaring vector<MyClass*> and writing:
MyClass *obj = new MyClass(args);
vec.push_back(obj);
But this would make me write a method to delete every instance of MyClass I created before, right?
So... What should I use and, if both are actually right, when one is preferrable to the other?
However, if everything is wrong from the start, how can I do this?
Thank yall!
PS: by the way, MyContainer is created in main(). I'm planning to use heap allocation. Should I?
Edit: I can't use C++11.
PS2: This is part of an assignment, but I found it general enough to be of use for anyone, not just me.
You probably shouldn't use new unless you need the object to survive beyond the local scope of the variable.
Just declare it on the stack:
MyClass obj(args);
vec.push_back(obj);
In C++11, you can avoid any risk of extra copies of obj by using:
vec.emplace_back(args);
Whether or not you should allocate on the heap or the stack as suggested by #happydave is highly dependent on the nature of "MyClass", IMO. If you need any kind of polymorphic behavior (i.e. you might have specialized subclasses of MyClass), then you should have a container of pointers.
If you're concerned about needing to delete each of the entries individually, there are two things that might help you:
1 . Use shared_ptr. So your code might look like this:
typedef std::shared_ptr<MyClass> MyClassPtr;
...
vector<MyClassPtr> vec;
vec.push_back(MyClassPtr(new MyClass());
The smart pointer will automatically delete MyClass when there are no more references to it.
2 . If you use bare pointers, you can still delete all the pointers with one line of code using std::for_each. This is described here: Can I call `delete` on a vector of pointers in C++ via for_each <algorithm>?
If you don't need polymorphic behavior and your class is copyable (either you gave it a copy constructor or the default copy is good for your implementation), then you can allocate on the stack.
I've been looking for documentation for cocos2d-x but it seems to be really really poor beyond the very basics. I understand that my own classes should inherit from CCObject to be able to use (originally cocoa's) retain/release mechanism, but I'm still confused about what happens when you new something. init is not called automatically. is it OK to call it from inside the constructor? does that alone guarantee that my object will start with a reference count of 1? what is CC_SAFE_DELETE and when should I use it? do release and autorelease work exactly like in cocoa? what about CC_SYNTHESIZE? I just need to see a properly coded class example (and it's instantiation/destruction) to understand what I'm supposed to do so as not to screw and leave memory leaks.
thank you.
If you will look to the code of CCObject class, you will see that in it's constructor reference count is set to 1 there. So, object creation with new is correct. Init is not called because CCObject class has no such a method. Usually I prefer to create objects using static constructor. Smth like
MyClass* MyClass::createInstance()
{
MyClass* object = new MyClass();
// you can create virtual init method
// and call it here
if( initWasSuccessful )
{
object->autorelease();
}
else
{
CC_SAFE_RELEASE_NULL(object);
}
return object;
}
About all macroses like CC_SAFE_DELETE - you can find them in the code of cocos2dx. This macros just check if object is NULL to prevent crash on trying to call release method.
The answer provided by Morion is great, I'd just like to add a few useful links about this matter.
Here you can find the official memory management in Cocos2d-x page:
Memory Management in Cocos2d-x
This forum page also contains some more details and clarifications about it:
Memory deallocation in Cocos2d-x
Enjoy coding!
If I have a factory, that creates an object and returns a pointer to it, what will be a better way to delete it:
By delete call in the "user" code, or by a new DestructObject function which I should have together with the factory?
In the general case, the factory might not use plain old new to allocate the object. It may use object and/or page pooling, malloc with placement new, or something even more exotic (memory mapping?). There are at least three ways to handle this that I can think of:
Have the factory supply a recycle method to be called when you are done with the object.
Return a smart pointer that knows how to do away with the object once no referers remain.
Implement a custom delete operator in the object itself.
I hesitate to recommend one over the other, since I haven't given it enough thought in the last five minutes to proffer a definitive opinion, but I would tend to favour the last option in combination with a regular smart pointer like boost/tr1::shared_ptr.
The best way to delete it manually would be not at all.
The following code provides an opportunity not to think about who should remove the newly created object.
class FooFactory
{
public:
static std::auto_ptr<Foo> CreateInstance();
};
// transmit ownership of created object from factory to 'a' variable
std::auto_ptr<Foo> a = FooFactory::CreateInstance();
// using the created object is not required
FooFactory::CreateInstance();
The most versatile solution for this problem is to derive your class from a base class that has a virtual "killing" function. Something like this:
class IDisposable {
public:
virtual void Release() = 0;
};
It's generally believed that polymorphic objects should have virtual destructors to support proper object cleanup. However this is incomplete, because it doesn't account for potentially different memory management of objects.
On the other hand this method doesn't require to use virtual destructors. It's now replaced by Release function that does both: invokation of the correct destructor and releasing the memory by the appropriate means.
takes care of the object destr
both: destruct
The object returned from the factory will implement this "interface".
This is also a question that I asked in a comment in one of Miško Hevery's google talks that was dealing with dependency injection but it got buried in the comments.
I wonder how can the factory / builder step of wiring the dependencies together can work in C++.
I.e. we have a class A that depends on B. The builder will allocate B in the heap, pass a pointer to B in A's constructor while also allocating in the heap and return a pointer to A.
Who cleans up afterwards? Is it good to let the builder clean up after it's done? It seems to be the correct method since in the talk it says that the builder should setup objects that are expected to have the same lifetime or at least the dependencies have longer lifetime (I also have a question on that). What I mean in code:
class builder {
public:
builder() :
m_ClassA(NULL),m_ClassB(NULL) {
}
~builder() {
if (m_ClassB) {
delete m_ClassB;
}
if (m_ClassA) {
delete m_ClassA;
}
}
ClassA *build() {
m_ClassB = new class B;
m_ClassA = new class A(m_ClassB);
return m_ClassA;
}
};
Now if there is a dependency that is expected to last longer than the lifetime of the object we are injecting it into (say ClassC is that dependency) I understand that we should change the build method to something like:
ClassA *builder::build(ClassC *classC) {
m_ClassB = new class B;
m_ClassA = new class A(m_ClassB, classC);
return m_ClassA;
}
What is your preferred approach?
This talk is about Java and dependency injection.
In C++ we try NOT to pass RAW pointers around. This is because a RAW pointer have no ownership semantics associated with it. If you have no ownership then we don't know who is responsible for cleaning up the object.
I find that most of the time dependency injection is done via references in C++.
In the rare cases where you must use pointers, wrap them in std::unique_ptr<> or std::shared_ptr<> depending on how you want to manage ownership.
In case you cannot use C++11 features, use std::auto_ptr<> or boost::shared_ptr<>.
I would also point out that C++ and Java styles of programming are now so divergent that applying the style of one language to the other will inevitably lead to disaster.
This is interesting, DI in C++ using templates:
http://adam.younglogic.com/?p=146
I think the author is making the right moves as to not translate Java DI into C++ too literally. Worth the read.
I've recently been bitten by the DI bug. I think it solves a lot of complexity problems, especially the automated part. I've written a prototype which lets you use DI in a pretty C++ way, or at least I think so. You can take a look at the code example here: http://codepad.org/GpOujZ79
The things that are obviously missing: no scoping, no binding of interface to implementation. The latter is pretty easy to solve, the former, I've no idea.
I'd be grateful if anyone here has an opinion on the code.
Use RAII.
Handing a raw pointer to someone is the same as handing them ownership. If that's not what you want to do, you should give them some kind of facade that also knows how to clean up the object in question.
shared_ptr<> can do this; the second argument of its constructor can be a function object that knows how to delete the object.
In C++, normally, when you done things right, you don't need to write destructors at all in most cases. You should use smart pointers to delete things automatically. I think, builder don't looks like the owner of the ClassA and ClassB instances. If you don't like to use smart pointers, you should think about objects life time and their owners.
Things get complicated if you don't settle on the question of ownership once and for all. You will simply have to decide in your implementation if it's possible that dependencies live longer than the objects they are injected into.
Personally I'd say no: the object into which the dependency is injected will clean up afterwards. Trying to do it through the builder means that the builder will have to live longer than both the dependency and the object into which it is injected. This causes more problems than it solves, in my opinion, because the builder does not serve any more useful purpose after the construction with the dependency injection has been completed.
Based on my own experience, it is best to have clear ownership rules. For small concrete objects, it is best to use direct copy to avoid cross dependency.
Sometimes cross dependency is unavoidable, and there is no clear ownership. For example, (m) A instances own (n) B instances, and certain B instances can be owned by multiple As. In this case, the best approach is to apply reference counting to B, in the way similar to COM reference counting. Any functions that take possession of B* must increase reference count first, and decrease it when releasing the possession.
I also avoid using boost::shared_ptr as it creates a new type (shared_ptr and B* become two distinct types). I found that it brings more headaches when I add methods.
You can also check the FFEAD Dependency Injection. It provides DI on the lines of Spring for JAVA and has a non-obtrusive way of dealing with things. It also has a lot of other important features like in-built AJAX Support,Reflection,Serialization,C++ Interpreter,Business Components For C++,ORM,Messaging,Web-Services,Thread-Pools and an Application Server that supports all these features.