Overloading new as a friend function? - c++

For one of my classes, I'm writing a program that's going to be using a templated memory pool structure to handle the allocation of new instances of a class while keeping them together. It is currently declared as follows:
template<typename T, unsigned int N>
class MemoryPool
{
//Stuff
};
Where T is the class to create this pool for and N is the maximum number of elements that can be placed in the pool. I want to overload new for the created type to make interactions with the pool a bit easier if it's a reasonable thing to do--but I'm not sure if it is.
My thoughts, currently, are that if it's possible to overload new as a friend function for Twithin MemoryPool that it should be doable from there but I'm not sure. And, I'm not sure of the best way to start setting that up. I've tried a few different ways to just declare the overloaded new and I'm getting errors before even implementing it.
Is this a reasonable way to ensure that new is overridden for any class that uses MemoryPool?
Is doing so even possible?
Is doing so even a good idea?
How would I set up the function declaration to accomplish this?
In case it matters, I'm using Visual Studio 2010.
Note, the specific use of templates and overloading new are not part of the homework assignment. It's just how I want to implement it if possible to make the rest of the assignment easier to read for the future. So, if there's no reasonable way to do it, I just use member functions within MemoryPool to accomplish the same goal.
Thanks!
Example implementation:
MemoryPool<Object, MAX_OBJECTS> objectPool; //Pool to store objects
Object* allObjects[MAX_OBJECTS]; //Locations of objects
//Make a new object (this is how I'd like to do it)
allObjects[0] = new Object(/*args*/);
//(If I can't do the above, this would be the alternative)
allObjects[0] = objectPool.AllocateNewSlot();
allObjects[0]->Initialize(/*args*/);
In this example, the use of the MemoryPool takes care of the actual implementation of new ensuring the Object is created in its pool instead of just anywhere on the heap (to ensure all the Objects are in a centralized, more controllable location.

It is possible to overload the new operator, however I would advice against it.
I think you are going in the wrong direction. You don't want to hide things and make users unsure what is happening. In this case you should be explicit that you are allocating through a pool.
Here is what you could do.
template<typename T, unsigned int N>
class MemoryPool
{
T* malloc()
{
return ... // your pool impl
}
void free(T* ptr)
{
... // your pool impl
}
void destory(T* ptr)
{
ptr->T::~T(); // call destructor
free(ptr);
}
};
int main()
{
MemoryPool<my_class> pool;
my_class* instance = new (pool.malloc()) my_class(/*args*/); // in-place new
return 0;
}
You should also take a look at how boost pool is implemented.

Related

Create myNew/myDelete to replace new/new[]/delete/delete[]

How to code my program to has flexibility to receive custom allocator in advance?
I coded some allocators, but not sure whether I will really need it.
However, I know for sure that if my custom allocator will be plugged-in, I want to use it in some certain parts.
Example
For example, int* B::db should use custom allocator (myNew/myDelete),
while all std::vector should use standard allocator.
While I still don't plug my custom allocator, I wish my program will use standard new/delete as default.
#define myNew new
#define myDelete delete
class B{ //B should not be a template class
int* db=nullptr;
std::vector<float> something; //<- let it use default new/delete
public: B(){
db=myNew int[5]; //work like "db=new int[5];"
}
public: ~B(){
myDelete[] db; //work like "delete[] db;"
}
};
If I want plug a custom allocator later, I can just change the #define.
Note: B should not be a template class.
Question
I am not sure if this is a correct way. I am still very new to allocator.
I also want to avoid macro if possible.
Is it a good solution? Are there solutions without macro?
I can let my program just use new/delete as default, and I can refactor it later.
However, it will probably be a mental-breaking work in the future.
Note: Most Q/A seem to focus on overloading the global new/delete. That is not what I want. :-
overloading new/delete
How to properly replace global new & delete operators
Using operator new and operator delete with a custom memory pool/allocator
Sorry if this question is too newbie.
I haven't found any good tutorial/information about using allocator in real practice.
I have also read (they are just theory of allocator + code) :-
https://www.gamedev.net/resources/_/technical/general-programming/c-custom-memory-allocation-r3010
http://allenchou.net/2013/05/memory-management-part-3-of-3-stl-compatible-allocators/
http://www.drdobbs.com/cpp/improving-performance-with-custom-pool-a/184406243?pgno=1
B may have to stay a non-template. But it doesn't mean you can't write a template to help. And you may as well facilitate RAII while you're at it.
template<typename T>
class my_new_heap_array {
T *ptr;
public:
operator T*() const { return ptr; }
my_new_heap_array(std::size_t sz)
: ptr(myNew T[sz])
{}
~my_new_heap_array() { myDelete[] ptr; }
};
class B { //B should not be a template class
my_new_heap_array<int> db;
std::vector<float> something; //<- let it use default new/delete
public:
B()
:db(5)
{ }
};
In general, so long as you program with separation of concerns in mind, you'd find it easier to change behaviors more easily. B needs to decide on what allocator to use, but it shouldn't be concerned with how to use it. That concern falls on the helper class. And if B needs to use another allocator some day, then just switch out the helper class for another.

Template Object of type function

So I'm making a application framework, every class basically inherits YObject, my Application manager handles any object that gets added to the class and stores them in: vector Application::ApplicationObjects`, I want to make a function like
ObjectType* object = Application->object_of<ObjectType>();
I'm not really sure how exactly to do this, I've heard one of the C++ casts can be used to determine if ObjectType derives from YObject, but I'm not sure!
EDIT:
Since its important to make understandable questions that can be researched or whatever..
What I was trying to make was a template function that would loop through all available objects and check if the current object could be cast to the template defined type.
I believe that you may have already found your answer here, but it may be beneficial to spell out how to do this for anyone else having the same issue.
You say that you want to:
Make was a template function that would loop through all available objects and check if the current looped object could be dereferenced to the template defined type
So let's start by assuming that you have pointers to all available objects in vector<YObject*> Application::m_foo, and you have pointers to a bunch of different objects in Application::m_foo.
You'll want to design your templated class like this:
template<typename T>
T* Application::object_of() {
T* result = nullptr;
for(auto& i : m_foo) {
T* bar = dynamic_cast<T*>(i);
if(bar != nullptr) {
result = bar;
break;
}
}
return result;
}
You can see a hacky example of this here: http://ideone.com/J4oA1j I say "hacky" cause rather than having an Application class I've just used a global variable, and I never delete my news. But I believe that the idea is clear.

Passing arbitrary data to a function without void pointers

I am working with an abstract base class implementing a set of system tests. In simplified form, the class declaration is:
class Test_Class
{
Test_Class();
~Test_Class();
Run_Test(void * param_set = NULL) = 0;
}
The base class requires the implementation of the Run_Test function which allows a user to pass in an arbitrary data structure as a void pointer and cast it to the appropriate type inside the body of Run_Test in a child class, in order to allow different tests to use different data structures, e.g. a float in one test vs a list of ints in another.
This is cumbersome and seems like an incredibly C-like way of doing things. Is there a better way of using inheritance or other language utilities?
Note: Due to customer constraints, this program is not allowed access to the STL or the Boost libraries.
Yes. User doesn't pass in an arbitary data structure but can make an arbitrary data structure by extending your base class.
class Test_Class {
Run_Test(const Config& config);
};
client code:
class MyConfig : public Config {
//...
};
Another option is templates. You can accomplish many common tasks with either, I'm not sure which is ideal in this situation so I'll leave it to other answers or to you to research that if you go this route.
If you want a set of tests, use std::vector<std::function<void()>> tests; and then you can simply tests.push_back([=] { do_test(the_args, I_captured, from_local, scope); });.
You can do similar tricks with std::bind if your compiler doesn't support lambdas.
There's no need for you, the end-user, to write your own generic function interface. It already has been done.
Edit: Yes, you're going to end up with some C-style garbage if you do not A) re-implement the wheels provided by Boost or the STL or B) use the existing wheels provided by Boost or STL. There is no magical third choice between "Write own good code" or "Use other people's good code" which still results in good code.
I dont remember is it possible/how to make argument detection for function inside class so maybe this will do:
class Test_Class {
public:
template <typename T>
void Run_Test(T p) {
}
};
template <class T>
void tester(Test_Class t, T p) {
t.Run_Test<T>(p);
}
int main() {
Test_Class p;
int a = 5;
tester(p, a);
}

WrapperPointer class and deallocation of stack-allocated objects in C++

I am designing a wrapper class (a bit similar to std::autoPtr but I have different purpose) for scalar values:
template <typename T>
class ScalarPtr
{
private:
T* m_data;
...
public:
ScalarPtr(T *data): m_data(data)
{ ... }
T& operator* ();
T* operator -> ();
~ScalarPtr()
{
if(m_data)
delete m_data; ...
}
};
Now the problem is that when I also want to use this class for stack-allocated memory objects like this:
float temp=...
ScalarPtr<float> fltPtr(&temp);
The naive way is to pass boolean in constructor to specify whether to deallocate or not but is there any better way?
I am not sure if there is a better approach other than the boolean flag.
As you are aware(and hence ask the Q)this makes the interface rather non-intutive to the end user.
The purpose of the wrapper/resource managing class is to implement an RAII, where the resource itself takes care of releasing its resources(in this case dynamic memory) implicitly. Given that the stack variables are automatically destroyed beyond their scopes,its seems rather odd to use a resource managing wrapper for them. I would rather not prefer to do so.
But, Given that you want to maintain a uniform acess to your class through this wrapper class, the simplest yet not so elegant way seems to be the boolean flag.

Possible to instantiate object given its type in C++?

I've been programming in Java way too long, and finding my way back to some C++. I want to write some code that given a class (either a type_info, or its name in a string) can create an instance of that class. For simplicity, let's assume it only needs to call the default constructor. Is this even possible in C++, and if not is it coming in a future TR?
I have found a way to do this, but I'm hoping there is something more "dynamic". For the classes I expect to wish to instantiate (this is a problem in itself, as I want to leave that decision up to configuration), I have created a singleton factory with a statically-created instance that registers itself with another class. eg. for the class Foo, there is also a FooFactory that has a static FooFactory instance, so that at program startup the FooFactory constructor gets called, which registers itself with another class. Then, when I wish to create a Foo at runtime, I find the FooFactory and call it to create the Foo instance. Is there anything better for doing this in C++? I'm guessing I've just been spoiled by rich reflection in Java/C#.
For context, I'm trying to apply some of the IOC container concepts I've become so used to in the Java world to C++, and hoping I can make it as dynamic as possible, without needing to add a Factory class for every other class in my application.
You could always use templates, though I'm not sure that this is what your looking for:
template <typename T>
T
instantiate ()
{
return T ();
}
Or on a class:
template <typename T>
class MyClass
{
...
};
Welcome in C++ :)
You are correct that you will need a Factory to create those objects, however you might not need one Factory per file.
The typical way of going at it is having all instanciable classes derive from a common base class, that we will call Base, so that you'll need a single Factory which will serve a std::unique_ptr<Base> to you each time.
There are 2 ways to implement the Factory:
You can use the Prototype pattern, and register an instance of the class to create, on which a clone function will be called.
You can register a pointer to function or a functor (or std::function<Base*()> in C++0x)
Of course the difficulty is to register those entries dynamically. This is typically done at start-up during static initialization.
// OO-way
class Derived: public Base
{
public:
virtual Derived* clone() const { return new Derived(*this); }
private:
};
// start-up...
namespace { Base* derived = GetFactory().register("Derived", new Derived); }
// ...or in main
int main(int argc, char* argv[])
{
GetFactory().register("Derived", new Derived(argv[1]));
}
// Pointer to function
class Derived: public Base {};
// C++03
namespace {
Base* makeDerived() { return new Derived; }
Base* derived = GetFactory().register("Derived", makeDerived);
}
// C++0x
namespace {
Base* derived = GetFactory().register("Derived", []() { return new Derived; });
}
The main advantage of the start-up way is that you can perfectly define your Derived class in its own file, tuck the registration there, and no other file is impacted by your changes. This is great for handling dependencies.
On the other hand, if the prototype you wish to create requires some external information / parameters, then you are forced to use an initialization method, the simplest of which being to register your instance in main (or equivalent) once you have the necessary parameters.
Quick note: the pointer to function method is the most economic (in memory) and the fastest (in execution), but the syntax is weird...
Regarding the follow-up questions.
Yes it is possible to pass a type to a function, though perhaps not directly:
if the type in question is known at compile time, you can use the templates, though you'll need some time to get acquainted with the syntax
if not, then you'll need to pass some kind of ID and use the factory approach
If you need to pass something akin to object.class then it seems to me that you are approaching the double dispatch use case and it would be worth looking at the Visitor pattern.
No. There is no way to get from a type's name to the actual type; rich reflection is pretty cool, but there's almost always a better way.
no such thing as "var" or "dynamic" in C++ last time I've checked(although that was a WHILE ago). You could use a (void*) pointer and then try casting accordingly. Also, if memory serves me right, C++ does have RTTI which is not reflection but can help with identifying types at runtime.