Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Use auto, or typedef? [closed]

I'd hate to ask an intentionally subjective question on here, but I don't have anyone else to ask this directly...

I'm trying to "lead by example" in my team by adopting more modern C++ concepts in new code I write. My coworkers are a bit shy of templates, and gripe about having to type unique_ptr<Foobar> or shared_ptr<Foobar> instead of just Foobar* when utilizing some classes I've recently created (factory methods return unique_ptrs and I store lists of these objects in vectors using shared_ptr).

They twisted my arm and convinced me to typedef these into something easier to type, eg FoobarUniquePtr.

But now I'm in a mess of const-correctness with these typedefs. I'd have to define extra typedefs for each const and non const type, and const const_FoobarUniquePtr doesn't seem to properly express the const semantics.

So, to my question, would it make sense to stop using these typedefs and instead shove auto at my teammates when they complain about having to type the templated smart pointers? I'm also open to other alternatives.

like image 427
Bret Kuhns Avatar asked Feb 16 '12 13:02

Bret Kuhns


People also ask

Can we use #define instead of typedef?

typedef is limited to giving symbolic names to types only, whereas #define can be used to define an alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc. typedef interpretation is performed by the compiler where #define statements are performed by preprocessor.

When should typedef be used?

Typedef allows flexibility in your class. When you want to change the data type in the program, you do not need to change multiple locations but just need to change one occurrence.

Is typedef faster than define?

They both take the same amount of time.

Is it good to use typedef?

The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.


1 Answers

In general, auto makes your life a lot easier.

If you aren't shipping on any esoteric architectures (and have no plans to do so anytime soon), the answer should be "use auto whenever you can".

like image 182
x10 Avatar answered Sep 24 '22 12:09

x10