Unreal Engine 4. Different ways to instantiate the object - c++

I found about four different ways to instantiate the object, but not sure if my understanding is clear.
NewObject<T>() function used when we want to make at the instance of UObject. For example, it can be any ActorComponents.
USomeComponent sc = NewObject<USomeComponent> (class);
ConstructObject<T>() one more way to init UObject...
CreateDefaultSubobject<T>() but using this one function we also can create an instance of any class inherited from UObject.
SpawnActor<T>() used for instantiating an object of AActor class.
So first question: What is the difference if we can use these functions for one purpose? How and when and why we need to use any of them?

To understand the difference between these functions, you need to remember that the object model
in Unreal Engine is based on object prototypes, very much like in JavaScript. Each UClass is associated
to a default instance of the associated UObject class, called the Class Default Object (CDO), which is
allocated first and then constructed, only once, via the class constructor when the engine is initialised.
The CDO acts as a template from which all other instances of the class are copied, and the constructor is
never called again.
This means class constructors cannot contain any runtime logic, and should only be used to
initialise the CDO and its properties. If the class contains any subobjects, like actor components,
these must do the same, so their own default objects must be constructed first. The actual instantiation of
the object must then be deferred, after the engine has initialised, so that every time a new instance of the class is
requested to be created by normal gameplay code, the parent object and all of its subobjects are instantiated from their respective defaults.
So, the multiple ways of creating objects are necessary to handle all the different
scenarios where an object may be created.
UObject::CreateDefaultSubobject is only callable in a class constructor, and takes care of creating an instance of the CDO
of the subobject's class, setting its outer class as the caller object,
among other things. The created object then becomes the default object for the property when its object class is instantiated.
NewObject<T> is the function normally used to instantiate objects after engine initialisation, during normal gameplay. It
provides several convenience overloads to handle most scenarios.
UWorld::SpawnActor<T> is a convenience method to spawn actors in a level with the specified location and rotation,
spawn collision settings, and checks to ensure it's a spawnable actor class, and is nothing more than a wrapper of
NewObject<AActor>.
ConstructObject has been removed in favour of NewObject.
I recommend checking the engine source code for more information, especially UObject/UObjectGlobal.cpp
and UObject/UObjectGlobal.h in the CoreUObject engine module. Internally, all these function ultimately call (as of 4.24)
StaticConstructObject_Internal, which handles the actual object creation.

Related

C++, pattern to initialize classes

In my code I'm implementing so many different classes that need to be initialized once the program's process is activated.
I am currently initiating manually each class, but they are so many, I thought that I could inherit from some class and each object created would be saved in a vector and could initalize the class from the object (base class) created, but I only need to initalize the class once, and even though I can set a flag for that, I dont think its a good solution.
Other solution that I thought is implement a kind of initializer on each class (static variable) that I have to initalize, same implementation, save the init object per class in a vector, and then init all the classes from the initializer class, but I have to pass to that object a lot of parametres and even functions.
so is a good solution but a bad implementing, think so.
so Do you know for some good pattern to initialize classes?
EDIT: EXAMPLE:
With Android and OpenGL, each time the app is not OnResume(), the Opengl context is destroyed, and OnResume() the context is recreated, and for any object that I need to render, I have a class for example 'Square class' that draws squares, and for each square object I have static variables in the 'Square class', that each square has access to be rendered properly with opengl, like buffers or shaders, etc, so any time the context is recreated, I need to reinitialize the class static variables in order that the object be rendered.
One standard pattern for initialisation in C++ is the nifty-counter pattern. See http://www.petebecker.com/js/js199905.html. To summarise, in your header file you define an object with a constructor, so this constructor will be executed once for each .cpp that includes the header file. This constructor increments a global shared counter. If the counter goes from 0 to 1 you run initialisation code. Similarly, the destructor decrements the counter, and de-initialises or destroys stuff when it goes from 1 to 0.
This works well with the only C++ guarantee about order of initialisation, which is that, within the same file, objects are constructed and initialised from top to bottom. If people have multiple .cpps which reference each other via header files, the first thing that gets initialised will be defined in a header that does not include anything else that needs initialisation first, which should be the something that does not depend on anything else.
Maybe I get this totally wrong, but at least in the Java world, one way of solving this topic is by using dependency injection via frameworks that take care of init'ting your objects, based on configuration information that you have to provide.
Meaning: you completely separate your actual "business logic" and the task of "establishing all the required objects". You don't do "new" any more in your code; all the important objects are created for you "by magic".
One example of such a framework for C++ would be fruit, which is actually inspired by Google's guice thing for java.

How might I verify that every instance of a given class is destructed by application termination?

I wrote a simplistic DBResourceMonitor class which is used by a set of database classes. When an instance of one of my database classes is created, it registers itself, and when destroyed, it unregisters itself with a singleton instance of DBResourceMonitor. When the application terminates, that global instance of DBResrouceMonitor is destroyed, which checks to make sure that there are no remaining registered instances of any of the classes that it monitors (i.e. that for every register, a unregister was called), and issues a TRACE output and ASSERT if there was a mismatch.
This is all well and good... until I put a couple of these database objects as members of my global application object. Hence, both the global application object, and the DBResourceMonitor are global singletons, and the application is the first to be constructed, hence the last to be destroyed, and hence when DBResrouceMonitor is destroyed, the members of the app object have yet to be unregistered, and so it throws an error indicating that there were mismatched register/unregister calls.
As far as I am aware, there is no way to ensure that the DBResrouceMonitor is constructed before the application object (and therefore destroyed afterwards).
Is this correct? Is there a clever way around that, or a way to rethink the above so that I can still track whether everything was taken care of before the final thread terminates?
Instead of having the objects register/deregister themselves with a singleton, you need to store the references to those objects in a collection property of the Singleton. So instead of doing:
var x = new MyDBObject();
you would use a factory pattern like:
var x = DBResourceMonitor.GetDBObject();
and somewhere in DBResourceMonitor you could manage a collection of MyDBObjects
MyDBObject GetDBObject()
{
//construct and save a MyDBObject or retrieve one from a list.
}
You could let the database object be the same as the resource monitor, by having a base class that "registers" the database object in its constructor, and "deregister" it in the (virtual) destructor. This way you can just create the object and not worry about singletons or extra monitor classes. The collection of objects would of course be a private static member in this base class, possibly protected in case of you using multi-threading.
I would also use std::unique_ptr instead of raw pointers, or possibly std::shared_ptr.

Employing constructors when initializing com components

I will describe the problem as simple as i can.
alright, here goes the problem;
Lets suppose we have a com component class with 3 of constructors where a constructor takes at least two of parameters. As we already know we instantiate the components via QueryInterface rather calling the classes' constructors therefore it seems it is not possible for a com client to set the constructor's parameters.
alright, here goes the question;
What is the best practical approach to allow a com client to instantiate a com component which requires at least two of parameters to be initialized?
Instead of directly returning object instances, your QueryInterface call can return factories. For example, instead of:
// implements IMyClass1 interface
return new MyClass1();
You would do:
// pointer to member that implements IMyClassFactory interface
return &m_myClassFactory;
// this could also be a static class instead of an object instance
The IMyClassFactory interface would have a create method that takes in the constructor arguments and returns the ultimate MyClass1 instance.
If its a pure COM component, the standard way of handling this is to implement Initialize(foo, bar) methods instead of separate constuctors and then call that immediately after COM instantiation. If the object has no sensible default state, then you can make it a member variable (pointer) in a COM object. From that COM object you will have your Initialize(foo, bar) functions. In each of these initialize function the correct version of your object will be instantiated. Every pass through function in your COM wrapper will need to check that your object is not NULL and return an appropriate HRESULT if it is.
One option would be to use a factory object; the creation functions would be all on the (stateless) factory object (on a different interface, of course), and pass back an initialized instance of the real object.
When I write COM servers, I don't usually allow my components to be instantiated by CoCreateInstance. Instead I export some bare functions (these can be described in IDL as well inside a module) from my DLL which accept the constructor parameters and return an interface pointer to the newly created object in an output parameter.
I like both Ates Goral's answer and Steve's and have upvoted both. Normally I would leave it at that, but I feel that this time I have to spell out my full take.
The "best", "right", "purest", "canonical" way to do this is undoubtely the factory pattern, as described by Ates. If you want to create a clean API, that's the road, hands down.
But... most of us are not busy creating public APIs for commercial products. For small internal projects with non-public APIs, I just want to get the job done. Having to implement an extra object just so I can expose a single factory method sounds rather overkill (particularly in C++). In most practical cases, I would just go for an Initialize(foo, bar) method as described by Steve. I would then make sure that every non-trivial method checks to see if the object has been initialized and returns a failure HRESULT if not.

how will Contained class call member function of containing class - Composition in C++

This is a general design question from C++ perspective. I have a container class which contains objects of 2 other classes.
From container class we can call methods of the contained class object "as we have handle to the contained class object" e.g. objContainedClass1->SomeMthod();
But I want to know how would the contained class object (objContainedClass1) access methods of container class.
I can think of following ways:
The container class object passes the pointer to itself (this pointer) to the contained class constructor. Using this pointer, the contained class can access the methods of container class.
Make some functions in the container class as static.
Any more ideas of achieving this?
Thanks
Don't, typically it is bad design for a class to have to know about its container. Usually it means you have broken the single responsibility principle.
Both ways are OK for different purposes. If all you need is to call static methods, #2 is OK. But if you need to access instance methods of container class, you need to have container class pointer, so #1 is the way.
In the case you need generic solution, implement observer pattern. In this case contained class doesn't know anything about container, it just raises events when necessary.
There are a number of bad-to-worse options.
You could make the contained classes part of the container class, if they are not used outside it.
You could make the container a friend of the contained classes (yuck).
You could pass in a reference or boost::shared_ptr to the container instead of a raw pointer. The best method depends on the lifetimes of each. Avoid raw pointers if you can.
What I would actually try to do is to isolate the interface of the container methods that the contained objects need to use (IContainerCallback, say), and use that as the link between the two. So the contained objects reference the container only indirectly, via an interface class that is decoupled from the implementation of the container.
Make some functions in the container class as static.
That's what can be called "goodbye OOP!" option and I refrain from using it as much as possible.
The container class object passes the pointer to itself (this pointer) to the contained class constructor. Using this pointer, the contained class can access the methods of container class.
Provided that the containing class implements an interface and contained classes know only the interface, I personally do not see any problem. In fact that is what I do myself. Obviously one has to be aware of the approach's gotchas, when e.g. contained object calls container's method during destruction of the latter (or any other moment of time when the container is in an intermediate state).
To further decouple the contained from the containing classes, events or messages could be used too. Contained objects do not know where they are contained, but instead send messages. Containing object when creating the contained objects registers itself as the recipient of the messages from them. That technique allows to make the objects literally independent, but requires (1) some messaging framework, (2) due to static nature of C++ rather elaborate to implement and (3) also needs additional level of documentation as interface of classes now includes messaging.
Otherwise, think twice why contained objects need to call container's methods. Could it be that you need to split off the container some generic functionality into 3rd class? If the contained objects are indeed the active objects and are the logical source of events in the system, then you might really need some basic event/messaging system to allow the container to efficiently poll for/monitor state changes in the contained objects.
Don't. The responsibility of a container class is to contain things, nothing else. If you need your container class to take actions based on what's contained within, have a third object perform those actions. For instance, I'm assuming that you're rearranging or otherwise modifying the collection of classes based on the contents of the classes. Instead of attempting to do so within the contained classes, perform this action in a class which uses the container as a dependency.

Maintaining a std::set<boost::shared_ptr>

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.