Difference between ATL CAutoPtr and STL std::auto_ptr? - shared-ptr

I'm writing some code in MFC and I want to use auto pointers. I've come across two different classes that look like they do the same thing: CAutoPtr and std::auto_ptr What are people's thoughts about the two different implementations?
Further, I know there is std::tr1::shared_ptr. Is there a similar shared_ptr that is in ATL/MFC?

Both CAutoPtr and auto_ptr give you smart pointer semantics including transfer of ownership semantics. CAutoPtr is an ATL class -- built using COM. It is a non-standard extension for a particular OS. auto_ptr on the other hand is standard C++. If you want to use a container of such objects you have to use CAutoPtrArray or CAutoPtrList.
An important point to note is that there is something called auto_ptr_ref that allows you to return auto_ptrs as a return value. There is no such thing with CAutoPtr.
auto_ptr is deprecated in C++0x. Use unique_ptr if you have to: you can use them in move-aware containers and also get some safety from unsafe implicit moves of l-values.

The closest thing to shared_ptr in ATL/MFC is CComPtr. It is meant to be used on COM objects, but it can be used on any class that includes AddRef/Release reference counting methods.

CAutoPtr is ATL specific .
std:auto_ptr and CAutoPtr both don't provide reference counting. It looks like both have same functionality.link text
I guess there is no shared_ptr in ATL/MFC. shared_ptr is implemented in boost library.

Related

What naming convention for a C API

We are working on a game engine written in C and currently we are using the following naming conventions.
ABClass object;
ABClassMethod(object, args)
AB Being our prefix.
Our API, even if working on objects, does not have inheritance, polymorphism or anything. All we have is data types and methods working on them.
Our Constants are named alike: AB_ConstantName and Preprocessor macros are named like AB_API_BEGIN. We don't use function like macros.
I was wondering how this was fitting as a C API. Also, you may note that the entire API is wrapper into lua, and you can either use the API from C or lua. Most of the time the engine will be used from lua.
Whatever the API you'll come out with, for your users' mental sanity (and for yours), ensure that it's consistent throughout the code.
Consistency, to me, includes three things:
Naming. Case and use of the underscore should be regulated. For example: ABClass() is a "public" symbol while AB_Class() is not (in the sense that it might be visible (for whatever reason) to other modules but it's reserved for internal use.
If you have "ABClass()", you should never have "abOtherClass()" or "AbYet_anotherClass()"
Nouns and verbs. If something is called "point" it must always be "point" and not "pnt" or "p" or similar.
Standard C library, for example, has both putc() and putchar() (yes, they are different but the name doesn't tell which one writes on stdout).
Also verbs should be consistent: avoid having "CreateNewPoint()", "BuildCircle()" and "NewSquareMake()" at the same time!
Argument position. If a set of related function takes similar arguments (e.g. a string or a file) ensure they have the same position. Again the C standard library do a poor job with fwrite() and fprintf(): one has the file as the last argument, the other as the first one.
The rest is much up to your taste and any other constraint you might have.
For example, you mentioned you're using Lua: Following a convention that is similar to the Lua one could be a plus if programmers have to be exposed to both API at the same time.
This seems standard enough. OpenGL did it with a gl prefix, so you can't be that far off. :)
There is a lot of C APIs. If you are creative enough to invent a new one, there's no "majority" to blame you. On the other hand, no matter which way you go there are enough zealots of other standards to get mad at you.

Does C's FILE have an object-oriented interface?

Does the FILE type used through standard C functions fopen, etc. have an object-oriented interface?
I'm looking for opinions with reasoning rather than an absolute answer, as definitions of OO vary by who you ask. What are the important OO concepts it meets or doesn't meet?
In response to JustJeff's comment below, I am not asking whether C is an OO language, nor whether C (easily or not) allows OO programming. (Isn't that a separate issue?)
Is C an object-oriented language?
Was OOP (object-oriented-programming) anything more than a laboratory concept when C and FILE were created?
Answering these questions will answer your question.
EDIT:
Further thoughts:
Object Oriented specifically means several behaviors, including:
Inheritence: Can you derive new classes from FILE?
Polymorphism: Can you treat derived classes as FILEs?
Encapsulation: Can you put a FILE inside another object?
Methods & Properties: Does a FILE have methods and properties specific to it? (eg.
myFile.Name, myFile.Size, myFile.Delete())
Although there are well known C "tricks" to accomplish something resembling each of these behaviors, this is not built in to FILE, and is not the original intent.
I conclude that FILE is not Object Oriented.
If the FILE type were "object oriented", presumably we could derive from it in some meaningful way. I've never seen a convincing instance of such a derivation.
Lets say I have new hardware abstraction, a bit like a socket, called a wormhole. Can I derive from FILE (or socket) to implement it. Not really - I've probably got to make some changes to tables in the OS kernel. This is not what I call object orientation
But this whole issue comes down to semantics in the end. Some people insist that anything that uses a jump-table is object oriented, and IBM have always claimed that their AS/400 boxes are object-oriented, through & through.
For those of you that want to dip into the pit of madness and stupidity that is the USENET comp.object newsgroup, this topic was discussed quite exhaustively there a few years ago, albeit by mad and stupid people. If you want to trawl those depths, the Google Groups interface is a good place to start.
Academically speaking, certainly the actual files are objects. They have attributes and you can perform actions on them. Doesn't mean FILE is a class, just saying, there are degrees of OO-ness to think about.
The trouble with trying to say that the stdio FILE interface qualifies as OO, however, is that the stdio FILE interface doesn't represent the 'objectness' of the file very well. You could use FILEs under plain old C in an OO way, but of course you forfeit the syntactic clarity afforded by Java or C++.
It should probably further be added that while you can't generate 'inheritance' from FILE, this further disqualifies it as OO, but you could argue that's more a fault of its environment (plain C) than the abstract idea of the file-as-object itself.
In fact .. you could probably make a case for FILE being something like a java interface. In the linux world, you can operate almost any kind of I/O device through the open/close/read/write/ioctl calls; the FILE functions are just covers on top of those; therefore in FILE you have something like an abstract class that defines the basic operations (open/read/etc) on an 'abstact i/o device', leaving it up to the various sorts of derived types to flesh those out with type-specific behavior.
Granted, it's very hard to see the OO in a pile of C code, and very easy to break the abstractions, which is why the actual OO languages are so much more popular these days.
It depends. How do you define an "object-oriented interface"? As the comments to abelenky's post shows, it is easy to construct an argument that FILE is object-oriented. It depends on what you mean by "object-oriented". It doesn't have any member methods. But it does have functions specific to it.
It can not be derived from in the "conventional" sense, but it does seem to be polymorphic. Behind a FILE pointer, the implementation can vary widely. It may be a file, it may be a buffer in memory, it may be a socket or the standard output.
Is it encapsulated? Well, it is essentially implemented as a pointer. There is no access to the implementation details of where the file is located, or even the name of the file, unless you call the proper API functions on it. That sounds encapsulated to me.
The answer is basically whatever you want it to be. If you don't want FILE to be object-oriented, then define "object-oriented" in a way that FILE can't fulfill.
C has the first half of object orientated.
Encapsulation, ie you can have compound types like FILE* or structs but you can't inherit from them which is the second (although less important) half
No. C is not an object-oriented language.
I know that's an "absolute answer," which you didn't want, but I'm afraid it's the only answer. The reasoning is that C is not object-oriented, so no part of it can have an "object-oriented interface".
Clarification:
In my opinion, true object-orientation involves method dispatch through subtype polymorphism. If a language lacks this, it is not object-oriented.
Object-orientation is not a "technique" like GTK. It is a language feature. If the language lacks the feature, it is not object-oriented.
If object-orientation were merely a technique, then nearly every language could be called object-oriented, and the term would cease to have any real meaning.
There are different definitions of oo around. The one I find most useful is the following (inspired by Alan Kay):
objects hold state (ie references to other objects)
objects receive (and process) messages
processing a message may result in
messages beeing sent to the object itself or other objects
a change in the object's state
This means you can program in an object-oriented way in any imperative programming language - even assembler. A purely functional language has no state variables, which makes oo impossible or at least awkward to implement (remember: LISP is not pure!); the same should go for purely declarative languages.
In C, message passing in most often implemented as function calls with a pointer to a struct holding the object's state as first argument, which is the case for the file handling api. Still, C as a language can't be classified as oo as it doesn't have syntactic support for this style of programming.
Also, some other definitions of oo include things like class-based inheritance (so what about prototypal languages?) and encapsulation - which aren't really essential in my opinion - but some of them can be implemented in C with some pointer- and casting magic.

C for an Object-Oriented programmer

Having learned Java and C++, I've learned the OO-way. I want to embark on a fairly ambitious project but I want to do it in C. I know how to break problems down into classes and how to turn them into class hierarchies. I know how to abstract functionality into abstract classes and interfaces. I'm even somewhat proficient at using polymorphism in an effective way.
The problem is that when I'm presented with a problem, I only way I know how to do it is in an Object-Oriented way. I've become too dependent on Object-Oriented design philosophies and methodologies.
I want to learn how to think in a strictly procedural way. How do I do things in a world that lacks classes, interfaces, polymorphism, function overloading, constructors, etc.
How do you represent complex concepts using only non-object-oriented structs? How do you get around a lack of function overloading? What are some tip and tricks for thinking in a procedural way?
The procedural way is to, on one side, have your data structures, and, on the other, your algorithms. Then you take your data structures and pass them to your algorithms. Without encapsulation, it takes a somewhat higher amount of discipline to do this and if you increase the abstraction level to make it easier to do it right, you're doing a considerable part of OO in C.
I think you have a good plan. Doing things the completely OO way in C, while quite possible, is enough of a pain that you would soon drop it anyway. (Don't fight the language.)
If you want a philosophical statement on mapping the OO way to the C way, in part it happens by pushing object creation up one level. A module can still implement its object as a black box, and you can still use reasonable programming style, but basically its too much of a pain to really hide the object, so the caller allocates it and passes it down, rather than the module allocating it and returning it back up. You usually punt on getters and setters, or implement them as macros.
Consider also that all of those abstractions you mentioned are a relatively thin layer on top of ordinary structs, so you aren't really very far away from what you want to do. It just isn't packaged quite as nicely.
The C toolkit consists of functions, function pointers and macros. Function pointers can be used to emulate polymorphism.
You are taking the reverse trip old C programmers did for learning OO.
Even before c++ was a standart OO techniquis were used in C.
They included defining structs with a pointer to srtuct (usually called this...)
Then defining pointer functions in the struct, and during runtime initialize those pointers to the relevant functions.
All those functions received as first paremeter the struct pointer this.
Don't think C in the complete OOP way. If you have to use C, you should learn procedural programming. Doing this would not take more time than learning how to realize all the OOP features in C. Furthermore, basic encapsulation is probably fine, but a lot of other OOP features come with overhead on performance when you mimic them (not when the language is designed to support OOP). The overhead may be huge if you strictly follow the C++ design methodology to represent every small things as objects. Programming languages have specific purposes in design. When you break the boundary, you always have to pay something as the cost.
Don't think you have to shelve your knowledge of object-oriented work - you can "program into the language".
I had to work in C after being primarily experienced in object-oriented work. C allows for some level of object concepts to pull through. At the job, I had to implement a red-black tree in C, for use in a sweep-line algorithm to find the intersection points in a set of segments. Since the algorithm used different comparison functions, I ended up using function pointers to achieve the same effect as lambdas in Scheme or delegates in C#. It worked well, and also allowed the balanced tree to be reusable.
The other feature of the balanced tree was using void pointers to store arbitrary data. Again, void and function pointers in C are a pain (if you don't know their ins and outs), but they can be used to approximate creating a generic data structure.
One final note: use the right tool for the job. If you want to use C simply to master procedural technique, then choose a problem that is well-suited to a procedural approach. I didn't have a choice in the matter (legacy application written in C, and people demand the world and refuse to enter the 21st century), so I had to be creative. C is great for low/medium abstractions from the machine, say if you wanted to write a command-line packet inspection program.
The standard way to do polymorphic behavior in C is to use function pointers. You'll find a lot of C APIs (such as the standard qsort(3) and bsearch(3)) take function pointers as parameters; some non-standard ones such as qsort_r take a function pointer and a context pointer (thunk in this case) which serves no purpose other than to be passed back to the callback function. The context pointer functions exactly like the this pointer in object-oriented languages, when dealing with function objects (e.g. functors).
See also:
Can you write object-oriented code in C?
Object-Orientation in C
Try not to use OOP in C. But if you need to, use structures. For the functions,
take a structure for an argument, like so:
typedef struct{
int age;
char* name;
char* dialog;
} Human;
void make_dialog(Human human){
char* dialog="Hi";
human.dialog=dialog;
}
which works exactly like python's self, or something like that and to access other functions belonging to that class:
void get_dialog(Human human){
make_dialog(human);
printf(human.dialog);
}

How one can achieve late binding in C language?

How one can achieve late binding in C language ?
Late binding is not really a function of the C language itself, more something that your execution environment provides for you.
Many systems will provide deferred binding as a feature of the linker/loader and you can also use explicit calls such as dlopen (to open a shared library) and dlsym (to get the address of a symbol within that library so you can access it or call it).
The only semi-portable way of getting late binding with the C standard would be to use some trickery with system() and even that is at least partially implementation-specific.
If you're not so much talking about deferred binding but instead polymorphism, you can achieve that effect with function pointers. Basically, you create a struct which has all the data for a type along with function pointers for locating the methods for that type. Then, in the "constructor" (typically an init() function), you set the function pointers to the relevant functions for that type.
You still need to include all the code even if you don't use it but it is possible to get polymorphism that way.
Symbol binding in C is always done at compile time, never runtime.
Library binding, or dynamic linking as it's called, is done via dlopen() and dlsym() on *nix, and LoadLibrary() and GetProcAddress() on Windows.
How one can achieve late binding in C language ?
The closest would be through dynamic loading of library (DLL) such as with dlopen & dlsym on Linux. Otherwise, it is not directly available in C.
Use Objective-C or Lua. Both are late-bound languages which can easily interface with C.
Of course you could implement your own name resolution scheme, but why re-invent the wheel?
Unfortunately you did not specify an OS. For Unix you can use shared libraries, or create a configurable (plugin) module structure. For details you may find the source code of an apache 1.3 webserver useful. http://httpd.apache.org/download.cgi
cppdev seems to be the one and only to hit the spot with his/her remark.
Please, have a look at the definition itself. In a few words:
Late binding, or dynamic binding, is a computer programming mechanism
in which the method being called upon an object is looked up by name
at runtime.
All other answers just miss the main point, that is "look up by name".
The needed solution would be very similar to a lookup table of pointers to functions along with a function or two to select the right one by name (or even by signature). We call it a "hash table".

What are the pitfalls and gotchas of mixing Objective-C and C?

At the risk of oversimplifying something I'm worried might be ridiculously complex, what should I be aware of when mixing C and Objective-C?
Edit: Just to clarify, I've never worked with C before, and I'm learning Objective-C through Cocoa. Also I'm using the Chipmunk Dynamics engine, which is C.
I'd put it the other way around: you might be risking overcomplicating something that is ridiculously simple :-)
Ok, I'm being a bit glib. As others are pointing out, Objective-C is really just a minimal set of language extensions to C. When you are writing Objective-C code, you are actually writing C. You can even access the internal machinations of the Objective-C runtime support using some handy C functions that are part of the language (no... I don't recommend you actually DO this unless you really know what you're doing).
About the only time I've ever had mildly tricky moments is when I wanted to pass an Objective-C instance method as a callback to a C function. Say, for example, I'm using a pure-C cross platform library that has functions which accept a callback. I might call the function from within an object instance to process some data, and then want that C function to call my instance BACK when its done, or as part of getting additional input etc etc (a common paradigm in C). This can be done with funky function wrapping, and some other creative methods I've seen, and if you ever need to do it googling "objective-c method for c callback" or something like that will give you the goods.
The only other word of advice is to make sure your objects appropriately manage any manually malloced memory that they create for use by C functions. You'll want your objective-c classes to tidy up that memory on dealloc if, indeed, it is finished.
Other than that, dust off any reference on C and have fun!
You can't 'mix' C and Objective-C: Objective-C is a superset of C.
Now, C++ and Objective-C on the other hand...
Objective C is a superset of C, so it shouldn't conflict.
Except that, as pointed here pure C has different conventions (obviously, since there is no built-in mechanism) to handle OO programming. In C, an object is simply a (struct *) with function pointers.

Resources