I am beginner for Visual C++ and currently just learning the concepts of it.
I came to know that there are 2 classes: Managed class & Value class.
Value classes are like normal C++ classes, whose objects can be created which will hold the data.
Managed classes are memory managed by garbage collector.
Questions:
Objects of the managed classes can't be created only handles can be created. Why is this?
Please give me brief idea about an instance? Is it just an object creation or something else?
It is not that you only create handles for managed classes, the instances (or objects) of the managed classes are created on the managed heap and you are given a handle to access that instance.
The full answer is a wiki entry in it's own right, but I'll try give you an idea of what the issues here are;
Managed vs. Value classes are C++/CLI (.Net) type classes. The reference documentation relating to C# and .Net is still valid here and will probably answer some of the more subtle questions here.
A "reference" you speak of is a .Net reference. Some people compare this to a pointer (a smart pointer) and that may help understand some of the code, but it is not a pointer.
Just because it is C++, doesn't mean the usual .Net rules don't apply. The mixed mode is there to allow code to cross the native/.Net boundary, but on either side the native/.Net, respectively, the rules still apply. Speaking from experience, try to keep this "contact" area small and specific helps in dealing with the subtleties and nuances when you try to have one foot in each camp.
Essentially, a managed class must have all it's members managed as well, since the garbage collection of this data is non-deterministic.
In a similar manner, "native data" in a mixed mode application cannot contain managed classes (or references).
gcroot and raw pointers are generally used to mix the two. RAII classes help to manage these elements, but can be specific to your project, so general solutions don't always help.
Related
I want to know which pointers point to a specific object at runtime in c/c++.
For example, I have an object A, now I want to do something for A, such as changing the memory address of A, at this moment I have to know there are how many pointer pointing to A, and,at least, the name of these pointers at runtime.
In fact I just want to realize the migration of an object or some data else, without making the program wrong. Because in c/c++ if I want to migrate an object A I must figure out how many pointer pointing to the object A, and than make these pointer pointing to the new address which is the address of the object A after migration.
Totally speaking, it likes the std::shared_ptr, and I also have realized a self-defined class to achieve this goal. But now, I just want to know are there some ways to achieve this goal by using some compiler tools such as LLVM, and without modifying the source code or modifying the source automatically.
*******problem description**********
In fact, I have two types of memory, typeA and typeB, and now I want to realize a function which can migrate an object X in typeA to typeB. To make sure the validity of programs, after migrating object X form typeA to typeB,I have to know how many pointers point to the object X and than make these pointers pointing to the new address of object X.
I want to know which pointers point to a specific object at runtime in c/c++.
In general this is not possible. BTW, it looks that you want to implement something quite similar to a precise copying garbage collector. If this is not clear to you, read the GC handbook (for the concepts and the terminology). Notice that variables (and their names) don't exist at runtime (only memory locations, perhaps on the call stack, are relevant then) but only at compile time.
Totally speaking, it likes the std::shared_ptr, and I also have realized a self-defined class to achieve this goal. But now, I just want to know are there some ways to achieve this goal by using some compiler tools such as LLVM, and without modifying the source code or modifying the source automatically.
Again, in general that is not possible. For an intuition about why, imagine that you deal with a union { Foo* fooptr; std::uintptr foonum; }; which is in fact discriminated by some arbitrary external property, like e.g. the oddness of your current pid. If you could solve that you have solved the halting problem. Read also about Rice's theorem. Both are very relevant for static source code analysis.
However, what you could do is define explicitly some additional strong coding rules and constraints, (perhaps with some support runtime library) and design and implement, e.g. with LLVM or some GCC plugin, a static analyzer which check against these coding rules and constraints.
Notice that in practice you can use some GCs with C++, e.g. Boehm's GC or
Ravenbrook's MPS.
Your question is still lacking a real motivation (which I am trying to guess) and looks like some XY problem. "Like a GC" is not enough.
See also this. Perhaps read about dynamic software updating or application checkpointing.
addenda
your problem (even with the problem description edit, I don't understand it well) looks similar to copying garbage collection techniques like Cheney's algorithm.
For this purpose, you can create a class which record amount of reference and every reference name. Like this
class custom_obj {
Custom A; // target object
int count_ptr; // reference count
vector<void*> ref_ptr; // reference pointer
};
That's a simple way.
I was thinking about passing an object to another object, and how it can get complicated. If object A and object B are created in the main class, and object A creates object C, how can I pass object C to object B? Or should I never create an object in another object and therefore never get too far away from the main class?
This got me thinking of a situation in which this might occur, but couldn't exactly match it up in my head, but I thought, what if I create two objects, and have a class that determines collision based on location properties of the objects. In the main class I can pass the two objects to the collision class, and then in the main class I can do some work based on the result. This makes sense, but is this the best way to find collision? Or should I make the collision class static?
Thanks for any replies to the two questions, sorry for not being more specific but I'm trying to wrap my head around the oop concepts.
The concept you are thinking of is called dependency injection. You are not the first one to think at this kind of problem of course.
Most of recent OOP frameworks handle that dependency injection for you. An example of implementation is to use configured services (SOA) in specific configuration files (JSON, YML, XML, ...) referencing your classes. Then the framework will instantiate all your services in the right dependency order for you!
If you want to code it by your own, you certainly should code a dependencyInjectionHandler or servicesContainer which do all the process of injecting objects into each others.
If you come from the PHP world, you can look at an implementation on Symfony2 for example.
Prefer Javascript? Take a look at Danf.
You should be able to find at least one existing implementation in almost all recent languages.
As the Dependency injection principle tells us - you should never create a Dependency (in you're case Object C) in your object, if you want to use another object you should inject it to the dependant object, this is called - inversion of control, the most popular and best practice is to inject you're dependencies in the constructor.
As to where you create them - like you suggested create them at the top (you're main function as you said) of you're a code and inject them all the way down. Depending on the language and framework you are using you can find lots of tools to help you manage it it a bigger scale app's - those tools usually called DI containers.
Good luck.
I've recently reread the interesting tutorial from Mike Ash about How to create classes at Objective-C Runtime
I has been a long time I am wondering where to apply this powerful feature of the language. I always see an overkill solution to most of the ideas that come to my mind, and I eventually proceed with NSDictionary. What are your cases of use of creating classes at runtime? The only one I see is an Obj-C interpreter... More ideas?
There's some possible options I see, when someone need to create class in runtime
To hide information about it (It won't help in most cases, but... you can)
To perform multiple-inheritance (If you really need it :)
Using your own language(i.e. some XML-like), that can be interpreted by your program, writted in Obj-C (Something like NSProxy, but even better.)
Creating some Dynamic-Class that can change it's behavior in runtime
In general.. There is some possible usages of this. But in real world, in default service applications there's no need to do this, actually:)
It could be used for example along Core Data or any API related to a database to create new classes of objects unknown at compilation time. However, I doubt this is used often, it's mostly the mechanism the system uses itself when it runs a program...
KVO, in the Cocoa frameworks, is implemented by dynamically creating "notifying" versions of your classes. See http://www.mikeash.com/pyblog/friday-qa-2009-01-23.html
We have developed a s/w architecture consisting of set of objects developed in C#. They make extensive use of events to notify the client of changes in status, etc.
The intention originally was to allow legacy code to use these managed objects through COM interop services. That was easy to write in the design specification but, I'm seeing that actually implementing it is more problematic. I've searched for many hours looking for a good sample of event handling using this method. Before we march down that path, I want to make sure that COM interop is the best way to allow legacy code to call our new code.
It appears there are several different options: 1) COM interop, 2) write unmanaged wrapper classes 3) use the /clr compiler switch to enable calling of managed objects, 4) use some sort of reverse pInvoke call. Am I missing any?
Each option will have its benefits & drawbacks and I'm wondering what the best way to go is. Here are specific questions/comments for each
COM INTEROP - It appears event handling is a hurdle. We use events that have variable types as parameters. An event parameter may have an event ID and an object. Based on the event ID, the object will be of a certain type. Can this be handled with COM interop? Many of the objects that are exposed have properties. You can't declare properties in an interface so all properties will need a corresponding get/set method.
WRITE UNMANAGED WRAPPER - I assume this means creating a DLL using the /clr option to allow creating and calling managed objects and exposing unmanaged objects. Would the client of these unmanaged. I haven't done this before. What are benefits/drawbacks of this?
USE THE /CLR SWITCH - I understand this means to add support for managed objects. What are the drawbacks of this approach? Does this option support events as described above? Can we say, "here's the managed library. Use the /clr compiler option with your legacy code and have at it?" I don't know the ramifications of this. Is there a good sample of how this works around? (I'm sure there is, I just haven't found it)
USE A REVERSE PINVOKE - I'm not sure exactly how this would work but, from what I've been able to find, this is not a likely valid solution.
So, what does the decision tree look like to find the correct direction? Any help is appreciated.
DP
I think your initial solution is the best one. COM interop is stable and reasonably well documented. All you need to do is ensure that all the different event objects that might pop out of a given event handler implement the same COM-visible base event object interface (that has the event type id, etc). From there, individual objects can implement whatever other interfaces they want, and your unmanaged code can QI for the right "detail" interface based on whatever criteria you want to define. It's really not that hard. Have a look at this CodeProject article for an end-to-end sample including unmanaged event handlers.
This is a question with many answers - I am interested in knowing what others consider to be "best practice".
Consider the following situation: you have an object-oriented program that contains one or more data structures that are needed by many different classes. How do you make these data structures accessible?
You can explicitly pass references around, for example, in the constructors. This is the "proper" solution, but it means duplicating parameters and instance variables all over the program. This makes changes or additions to the global data difficult.
You can put all of the data structures inside of a single object, and pass around references to this object. This can either be an object created just for this purpose, or it could be the "main" object of your program. This simplifies the problems of (1), but the data structures may or may not have anything to do with one another, and collecting them together in a single object is pretty arbitrary.
You can make the data structures "static". This lets you reference them directly from other classes, without having to pass around references. This entirely avoids the disadvantages of (1), but is clearly not OO. This also means that there can only ever be a single instance of the program.
When there are a lot of data structures, all required by a lot of classes, I tend to use (2). This is a compromise between OO-purity and practicality. What do other folks do? (For what it's worth, I mostly come from the Java world, but this discussion is applicable to any OO language.)
Global data isn't as bad as many OO purists claim!
After all, when implementing OO classes you've usually using an API to your OS. What the heck is this if it isn't a huge pile of global data and services!
If you use some global stuff in your program, you're merely extending this huge environment your class implementation can already see of the OS with a bit of data that is domain specific to your app.
Passing pointers/references everywhere is often taught in OO courses and books, academically it sounds nice. Pragmatically, it is often the thing to do, but it is misguided to follow this rule blindly and absolutely. For a decent sized program, you can end up with a pile of references being passed all over the place and it can result in completely unnecessary drudgery work.
Globally accessible services/data providers (abstracted away behind a nice interface obviously) are pretty much a must in a decent sized app.
I must really really discourage you from using option 3 - making the data static. I've worked on several projects where the early developers made some core data static, only to later realise they did need to run two copies of the program - and incurred a huge amount of work making the data non-static and carefully putting in references into everything.
So in my experience, if you do 3), you will eventually end up doing 1) at twice the cost.
Go for 1, and be fine-grained about what data structures you reference from each object. Don't use "context objects", just pass in precisely the data needed. Yes, it makes the code more complicated, but on the plus side, it makes it clearer - the fact that a FwurzleDigestionListener is holding a reference to both a Fwurzle and a DigestionTract immediately gives the reader an idea about its purpose.
And by definition, if the data format changes, so will the classes that operate on it, so you have to change them anyway.
You might want to think about altering the requirement that lots of objects need to know about the same data structures. One reason there does not seem to be a clean OO way of sharing data is that sharing data is not very object-oriented.
You will need to look at the specifics of your application but the general idea is to have one object responsible for the shared data which provides services to the other objects based on the data encapsulated in it. However these services should not involve giving other objects the data structures - merely giving other objects the pieces of information they need to meet their responsibilites and performing mutations on the data structures internally.
I tend to use 3) and be very careful about the synchronisation and locking across threads. I agree it is less OO, but then you confess to having global data, which is very un-OO in the first place.
Don't get too hung up on whether you are sticking purely to one programming methodology or another, find a solution which fits your problem. I think there are perfectly valid contexts for singletons (Logging for instance).
I use a combination of having one global object and passing interfaces in via constructors.
From the one main global object (usually named after what your program is called or does) you can start up other globals (maybe that have their own threads). This lets you control the setting up of program objects in the main objects constructor and tearing them down again in the right order when the application stops in this main objects destructor. Using static classes directly makes it tricky to initialize/uninitialize any resources these classes use in a controlled manner. This main global object also has properties for getting at the interfaces of different sub-systems of your application that various objects may want to get hold of to do their work.
I also pass references to relevant data-structures into constructors of some objects where I feel it is useful to isolate those objects from the rest of the world within the program when they only need to be concerned with a small part of it.
Whether an object grabs the global object and navigates its properties to get the interfaces it wants or gets passed the interfaces it uses via its constructor is a matter of taste and intuition. Any object you're implementing that you think might be reused in some other project should definately be passed data structures it should use via its constructor. Objects that grab the global object should be more to do with the infrastructure of your application.
Objects that receive interfaces they use via the constructor are probably easier to unit-test because you can feed them a mock interface, and tickle their methods to make sure they return the right arguments or interact with mock interfaces correctly. To test objects that access the main global object, you have to mock up the main global object so that when they request interfaces (I often call these services) from it they get appropriate mock objects and can be tested against them.
I prefer using the singleton pattern as described in the GoF book for these situations. A singleton is not the same as either of the three options described in the question. The constructor is private (or protected) so that it cannot be used just anywhere. You use a get() function (or whatever you prefer to call it) to obtain an instance. However, the architecture of the singleton class guarantees that each call to get() returns the same instance.
We should take care not to confuse Object Oriented Design with Object Oriented Implementation. Al too often, the term OO Design is used to judge an implementation, just as, imho, it is here.
Design
If in your design you see a lot of objects having a reference to exactly the same object, that means a lot of arrows. The designer should feel an itch here. He should verify whether this object is just commonly used, or if it is really a utility (e.g. a COM factory, a registry of some kind, ...).
From the project's requirements, he can see if it really needs to be a singleton (e.g. 'The Internet'), or if the object is shared because it's too general or too expensive or whatsoever.
Implementation
When you are asked to implement an OO Design in an OO language, you face a lot of decisions, like the one you mentioned: how should I implement all the arrows to the oft used object in the design?
That's the point where questions are addressed about 'static member', 'global variable' , 'god class' and 'a-lot-of-function-arguments'.
The Design phase should have clarified if the object needs to be a singleton or not. The implementation phase will decide on how this singleness will be represented in the program.
Option 3) while not purist OO, tends to be the most reasonable solution. But I would not make your class a singleton; and use some other object as a static 'dictionary' to manage those shared resources.
I don't like any of your proposed solutions:
You are passing around a bunch of "context" objects - the things that use them don't specify what fields or pieces of data they are really interested in
See here for a description of the God Object pattern. This is the worst of all worlds
Simply do not ever use Singleton objects for anything. You seem to have identified a few of the potential problems yourself