Maintaining a std::set<boost::shared_ptr> - c++

I'm writing a game and an accompanying engine in C++. The engine relies heavily on automation using a simple embedded scripting language. Scripts can create object classes, define event listeners on them, and produce instances from them. At present, an instance must be bound to a script-global identifier in order to preserve its existence. The obvious result of this is that there can be no anonymous objects, which will be by far the most common.
At present, instances are managed using a std::set<Instance*, spatial_sort>, where spatial_sort is a functor that sorts instances by position, for rendering and collision detection. Instances are removed and re-inserted each frame using their current position as a hint, under the assumption that they're not likely to move a whole lot in a fiftieth of a second. If a dead flag is set in the instance, it is erased from the set. The Instance constructors and destructor invoke insert(this) and erase(this), respectively.
In order to allow anonymous instances, I want to change the set to a std::set<boost::shared_ptr<Instance>, spatial_sort>, which would allow Instance to share ownership of instances and preserve their existence until they destroy themselves. Unfortunately, because the calls to insert() need to be placed in the constructor, shared_from_this() won't work for obtaining a shared_ptr to the Instance. It doesn't matter at all that Instance happens to already inherit from boost::enable_shared_from_this<> via its base class.
Can anyone recommend a suitable workaround?
Edit:
I did what I should have been doing in the first place, and split the behaviour of the Instance class into two classes: Instance and Reference. The expression new SomeClass in a script then returns a Reference to a new Instance. The Instance objects themselves are never managed using a shared_ptr, so they are responsible for committing suicide in response to a suitable event, e.g., end of animation, end of level, etc.
Thanks for the help! Refactoring is as good a solution as any if it Just Works.

You could add a static method to Instance that you then use to create new objects and that also does the administrative stuff like adding it to the set:
static Instance* create(int something) {
boost::shared_ptr<Instance> sptr(new Instance(something));
instanceset.insert(sptr);
return sptr.get();
}
If you want to make this the only way to construct an object of this class you could also make the normal constructor private or protected.
For more on this see also the C++ FAQ Lite entry about "Dynamic binding during initialization", which is not directly related but uses the same technique to work around the restrictions on the use of virtual functions in constructors.

Related

Object propagation

I have a collection of objects, lets say QVector<ApplicationStates>, which registers the most important operations done in my software. Basically, this object is meant to process redo/undo operations.The application is built using a lot of delegated objects. Operations which have to be registered lie in a lot of these objects. As such, I am always passing my collection of objects, in each delegate under the form:
class AWidget : public QWidget{
AWidget(QVector<ApplicationStates>* states, QWidget* parent = nullptr);
...
It seems ugly to me. I think about two solutions:
Singleton;
Simply declare the QVector as a static global variable (I read that global variables are evil).
Does someone have a suggestion?
Thanks for your answers.
I get into a similar situation from time to time, and I have found simply wrapping your vector in a class called something like "ApplicationContext" then passing a shared pointer or reference to an instance of that around saves the day. It has many benefits:
You avoid the global / singleton, and you are free to in fact have several instances concurrently in the future
If you suddenly have more than just that vector of objects that you need to pass arround, simply extend your context class to add whatever you need
If your vector suddenly becomes a map or changes in other ways, you need not change any interfaces that pass it along such as the signals/slots. (You will need to change the implementation where the vector is used of course).
BONUS: The code becomes easily testable! You can now make test cases for this class.
This might not be the best solution in all cases, but I think it comes pretty close in this case!

Should a member of a class, that is expensive to create and will after creation never change, be static const?

I've a class that has a member of type std::map. This map is created through calling a method of this class, makeMap(). It reads a config file and fills the map.
In my scenario, I create one instance of this class and construct the map. Then recursively some problem is solved, involving many copies of the object. The map however stays the same (some other members are change).
Should such a map be static const? Since it does not change after creation and creation could be done when the first instance is created, it makes no sense to copy the map when the instance is being copied.
Is that a good use of static const?
No. The reason is testability and coupling.
By making it static, you are preventing injecting a mock while testing. You are also making it harder for future changes to go in easily.
Especially since it's expensive to create, you dont want to do that while testing. You would want to inject a Mock or a Fake.
This is true even if it's const. Maybe one day it won't be?
You can read about the downsides of global state here:
https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil
Now for practicality, if you want that map to be created just once but have many instances of your object, you could create it in main() and use dependency injection and pass it in the constructor.
You could also use the Builder design pattern to solve this issue (while the builder could hold the map as a static object)

Singleton or passing pointers to static reference in manager

I have a connection manager which currently has a static reference to a class which is kept inside the connection manager in the private section of the class. A pointer to this class is passed to all connections and they can use it for utility purposes.
Now this class pointer is not immediately useful to the childs, but it is useful for the childs own children, so all that happens is that it's passed along.
Now I'm wondering that since there is only ever 1 instance of this utility class should I bother with all this passing around of the pointer, or would it be better to make the class a singleton and each class that requires it can simply use a static getInstance() method instead. This would mean that classes that don't care about it don't need to know about it.
There are lots of types of connections (30+) and none of them care about the utility class.
However, they will use classes (at the moment, just 2) that do care about the utility class.
I'm not sure if every type of connection should burden itself with something it doesn't care about, just for the sake of a couple of classes that it (may) use.
Singletons and static fields are generally considered evil. Why is it static anyway? It could happen so one day you'll need each connection manager to have its own reference.
The best idea I can think of is to make the reference non-static first. Then, forget about using the singletons. From this point you should start to think how to implement this in the most elegant way.
I don't know the nature of your class, but it sounds reasonable to me that each connection should have a reference (or a pointer) to the connection manager that manages it. Just in case.
Then, the connection manager should probably provide a getter for anyone who wants to access that utility class. Connections themselves should pass along either the reference to the connection manager or to the utility class depending on what makes more sense.
It also makes sense to pass the reference to the connection manager to the constructor of the common ancestor of the connections, if there is one (which it should be). This way, you no longer have 30+ classes that refer to something they don't really need, but just one abstract class that they are based upon.
And if you really want to do something singleton-like, then it's better to have a kind of static method with a parameter that returns the reference, as opposed to just a static method:
static UtilityClass *getInstance(int id);
// not static UtilityClass *getInstance();
Even if you don't use the id parameter right now, it may get very useful later, when you need multiple instances. You could have some sort of table or hash map that maps the id to the instance. You can even add a method that creates or replaces the instance for a specific id, which could be very useful for unit testing. Note that this approach still has at least the following disadvantages of the singleton pattern:
It is prone to various threading problems.
It still hides dependencies of your classes: that is, you can't say what a class uses just by looking at its API.
It is hard to give more advices without looking at the code.
If I understand you correctly, at the top layer there is a Connection Manager. It contains a static class which is useful later on.
The next layer down are many instances of a class which exists to service each of the connections managed by the aforementioned manager.
Each one of those may in turn use some instances of utility classes which would like access to information from the Connection Manager (in this case you've wrapped it up as the static object).
The question is how best should the 3rd layer down should gain access to the Connection Manager's contained information.
I'll call them: Manager (contains 'static class') -> Connection -> Utility
My suggestion would be to have the Connections take references to the Manager which owns them. They can't or shouldn't exist without it and they are managed by it. They in turn need to construct objects that need a specific bit of information from the Connection Manager (the static class contained within).
So when the Connection's construct the Utility classes, the Utility classes will require only the bit of information they need to operate (in this case a reference parameter for a class which happens to be static inside the Manager). They should take this by reference also. The Connection has the Manager class reference and is able to provide the constructor for the Utility the bit of information it needs to operate.
The reason I am suggesting this approach is:
Connections/Utility classes don't care whether the manager is a singleton (opens possibilities later if you need multiple managers)
Utility doesnt care whether static class is static. They only need a reference to a specific class they need.
Manager decides how it or its contained data needs to be allocated.
Lastly:
The only class which has reason to know about the other two main classes is the Connections class. It seems reasonable it might know which manager is managing it (and therefore some interface information). It also knows what the Utility classes it will require and what they will need in terms of construction params and other interface requirements.
To set this up there may be some funkiness with includes and classes may have to expose interfaces to each other but thats just standard fare anyway.
My 2c.
Singleton vs. Static
A good example of singleton usage: you wish only one instance to be running for a class, for example a texture manager, shader manager, connection pool manager etc. (see the pattern emerging:)
As an example lets take a connection pool manager: we want to create a single pool of connections that are managed and re-used by any other object that requires a connection in our code, so we make a ConnectionPoolManager singleton class, with say, 32 connections. This now allows every object requiring a connection to use a method, for example getFreeConnection, from the ConnectionPoolManager singleton, to retrieve a valid connection which can then be used as needed. This allows the ConnectionPoolManager to be the only part of the code anywhere that has anything to do with starting stopping and otherwise managing connections for your code.
Both singletons and static class can be implemented in such a way that they are thread-safe, however singletons have the advantage as they can implement interface (common), derive from other classes (less common), and a singleton can be passed around in exactly the same way as any other object (well a reference to it at least), where a static class can only implement static methods.
In regards of your specific case, you indicate that from 30+ classes only a couple require the utility class: the dependence on a singleton or static class is entirely up to your design and style. Should you wish a versatile way of doing it, with potential for change later, I would utilise a singleton. If you know that the static class will suffice and will not necessitate a redesign later, then go with that, or, if you have a particular liking for one or the other, use that one. There may also be hardware/software limitations and particulars which recommend one over the other, however that does not sound to be the case at the moment.
Let me know if you need more information, or if there are any particulars which you think may sway your choice one way or the other and I can provide information about pros and cons for each approach to suit your needs:)

Proxy pattern - Applicability & Examples

From here: http://www.oodesign.com/proxy-pattern.html
Applicability & Examples
The Proxy design pattern is applicable when there is a need to control
access to an Object, as well as when there is a need for a
sophisticated reference to an Object. Common Situations where the
proxy pattern is applicable are:
Virtual Proxies: delaying the creation and initialization of expensive
objects until needed, where the objects are created on demand (For
example creating the RealSubject object only when the doSomething
method is invoked).
Protection Proxies: where a proxy controls access to RealSubject
methods, by giving access to some objects while denying access to
others.
Smart References: providing a sophisticated access to certain objects
such as tracking the number of references to an object and denying
access if a certain number is reached, as well as loading an object
from database into memory on demand.
Well, can't Virtual Proxies be created by creating an individual function (other than the constructor) for a new object?
Can't Protection Proxies be created by simply making the function private, and letting only the derived classes get the accesses? OR through the friend class?
Can't Smart References be created by a static member variable which counts the number of objects created?
In which cases should the Proxy method be preferred on the access specifiers and inheritance?
What's the point that I am missing?
Your questions are a little bit abstract, and i'm not sure i can answer at all well, but here are my thoughts on each of them. Personally i dont agree that some of these things are the best designs for the job, but that isn't your question, and is a matter of opinion.
Virtual Proxies
I don't understand what you are trying to say here at all. The point of the pattern here is that you might have an object A that you know will take 100MB, and you don't know for sure that you will ever need to use this object.
To avoid allocating memory for this object until it is needed you create a dummy object B that implements the same interface as A, and if any of its methods are called B creates an instance of A, thus avoiding allocating memory until it is needed.
Protection Proxies
Here i think you have misunderstood the use of the pattern. The idea is to be able to dynamically control access to an object. For example you might want class A to be able to access class B's methods unless condition C is true. As i'm sure you can see this could not be achieved through the use of access specifiers.
Smart Referances
Here i think you misunderstand the need for smart pointers. As this is quite a complicated topic i will simply provide a link to a question about them: RAII and smart pointers in C++
If you have never programmed in a language like C where you manage your memory yourself then this might explain the confusion.
I hope this helps to answer some of your questions.
EDIT:
I didn't notice that this was tagged c++ so i assume you do in fact recognize the need to clean up dynamic memory. The single static reference count will only work if you only intend to ever have one instance of your object. If you create 2000 instances of an object, and then deleted 1999 of them none of them would have their memory freed until the last one left scope which is clearly not desirable (That is assuming you had kept track of the locations of all the allocated memory in order to be able to free it!).
EDIT 2:
Say you have a class as follows:
class A {
public:
static int refcount;
int* allocated_memory;
A() {
++refcount;
allocated_memory = new int[100000000];
}
~A() {
if(! --refcount) {
delete [] allocated_memory;
}
}
}
And some code that uses it:
int main() {
A problem_child; // After this line refcount == 1
while(true) {
A in_scope; // Here refcount == 2
} // We leave scope and refcount == 1.
// NOTE: in_scope.allocated_memory is not deleted
// and we now have no pointer to it. Leak!
return;
}
As you can see in the code refcount counts all references to all objects, and this results in a memory leak. I can explain further if you need, but this is really a seperate question in its own right.
I am no expert, but here are my thoughts on Virtual Proxies : If we control the initialization via a separate function say bool Create(); then the responsibility and control of Initialization lies with the client of the class. With virtual proxies , the goal is to retain creation control within the class, without client being aware of that.
Protection Proxies: The Subject being protected might have different kinds of clients, ones which need to get unprotected/unrestricted access to all Subject methods and the others which should be allowed access to a subset of methods hence need for Protection proxy.
A proxy is an object behaving as a different object to add some control/behavior. A smart pointer is a good example: it accesses the object as if you would use a raw pointer, but it also controls the lifetime of that object.
It's good to question whether there are alternatives to standard solutions to problems. Design Patterns represent solutions that have worked for many folks and have the advantage that there's a good chance that an experienced programmer coming to the code will recognize the pattern and so find maintaining the code easier. However, all designs represent trade-offs and patterns have costs. So you are right to challenge the use of patterns and consider alternatives.
In many cases design is not just about making code work, but considering how it is structured. Which piece of code "knows" what. You proposal for an alternative for Virtual Prozy moves (as fizzbuzz says) knowledge of creation from the proxy to the client - the client has to "know" to call Create() and so is aware of the life-cycle of the class. Whereas with the proxy he just makes an object that he treats as the worker, then invisibly creation happens when the proxy decides it makes sense. This refactoring of responsibility into the proxy is found to valuable, it allows us in the future to change those life-cycle rules without changing any clients.
Protection proxy: your proposal requires that clients have an inheritance relationship so that they can use protected methods. Generally speaking that couples client and worker too tightly, so we introduce a proxy.
Smart reference: no, a single static count is no good. You need to count references to individual instances.
If you carefully work through each case you will find there are merits to the design patterns. If you try to implement an alternative you start with some code that sems simpler that the design pattern and then discover that as you start to refactor and improve the code, removing deuplicationand so on you end up reinventing the design pattern - and that's a really nice outcome.

C++: Unsure about class - class manager relationship

In my project I have a series of classes where their instances are manged by some manager class, for specific reasons.
Examples would be:
CSound - Abstracts a single sound
CSoundManager - Friend of CSound,
provides factory methods for creating
CSound instances, mixes active sounds
together
Also: CFont, CFontManager (for font access per-name), CSprite, CSpriteManager (for drawing each frame), and so on.
Here my first questions already:
Is what I'm doing a specific named design-pattern?
Is it in most cases, for whatever reason, a bad idea? If yes, why?
Then, I have asked myself:
How should the objects be created and destroyed? Should I permit creating them on the stack or directly with new, or only by the methods of the corresponding manager class?
(also for destruction: delete myFont; versus. FontManager.DestroyFont( myFont );)
Sounds like you may be violating the The Single Responsibility Principle (SRP) principle.
Is the CSoundManager class responsible for creating and managing the lifetime of CSound objects, or is it in charge of mixing active sounds together? Names can tell you much, and "Manager" can be understood in too many ways...
Generally, if you want these Manager classes to handle the lifetimes of your objects, then they should most likely be the only way to instantiate these objects (i.e. private ctors in the objects). See the Factory Design Pattern, although your implementation is a bit different.
If you do this, then the client code should never call new or delete. Manually calling delete is bug-prone, and should be avoided using idioms such as RAII. In this particular case, the Manager class should manage the lifetime of objects, and therefore delete will never appear in client code.
Looks like you are using some form of Factory design pattern. Not sure what makes you feel its a bad idea.
If you are treating Manager as container of the objects then it would control the life cycle of these objects. However if your objects need to live beyond the life of Manager then you would create them with new and Manager may not be responsible for destruction.
Generally what you're implementing is a Factory Method Pattern wherein an object allocates another object. However, you are not reaping the benefits of a Factory class as you're directly tying the allocated type to the factory as opposed to allowing the factory to manage all the internals abstractly. For instance, can you do this from any file, or just the factory for that resource type (CSoundManager): new CSound();
If so, you're missing the point and you basically just have a Singleton that allocates and manages an object. Consider abstracting your resource types. If CSound and CFont derived from IResource, you could have a CResourceManager that would just take an enum or some sort of identifier for that type and reduce coupling and dependencies in your codebase. Whenever you needed to use that object you could expose the type but more likely than not you could use an abstract manager (CResourceManager) to handle those objects using common interfaces (Update(), Create(), Destroy() etc...).
For your sound manager case, remember that sounds need only be loaded once and can be instanced with a unique state. In that right, have the resource manager manage the actual resource (CSound), and the sound manager (CSoundManager) maintain discrete instances (e.g. CSoundInstance) and manage mixing (via CSoundMixer). Specialize your classes in meaningful ways that manage complexity and reduce redundancy.
I used the sound manager as an example but this holds true for most io systems (graphics, input, physics).