Saturday, 8 August 2015

My witty side....

8th August 2015
Manager : Sorry, I can't promote you.
Employee : Why?
Manager : There were better candidates.
Employee : Define "better".
Manager : Better is a benchmark which is relative and ambiguous to suit any theory.
Employee : You are so "better" person.


7th August 2015
LIFE is never fair, it was never meant to be fair.

Stand against wrongs and DO NOT fear the fear.
FIGHT such fear so to make the life fair.
Come what may there is nothing to fear…
“हानि लाभ जीवन मरण यश अपयश सब विधि हाथ” ~रामचरितमानस


6th August 2015

Apparently pornography ban is only opposed by so called civil society. Salute to Poonam Pandey and Sunny Leone.


22nd July 2015
You can live a good life, be honorable, give to charity,
but in the end, the number of people
who come to your funeral is generally dependent on the weather.


19th April 2015

Sonia G understands farmers pain, apparently her crop is destroyed too.‬


24th August 2014

Teacher: Sodium ka chemical formula pata hai?
Me: Naah. 
Teacher: Correct!
Joke samajh na aaye to koi nahi. School me padhta kaun tha?


13th April  2014

It can happen only in Chicago that you live at 26th floor and still be surrounded by buildings. Skyscrapers till I see...
— at Bridgestreet State & Grand, Chicago.


15th November 2013

Okay Indians back to work....and American Indians go to sleep ‪#‎ThankyouSachin‬‬


20th October 2013

Trust Chinese products for letting you down ‪#‎GravityMovie‬‬


16th Ocotber 2013

Bakra to @iamsrk : Kab takk hai jaan ‪#‎EidMubarak‬‬


20th September 2013

Android is powerful. iOS is for pocket full.......


7th September 2013

Raanjhanaa: O Rikshawale, madam se paise mat lena.
Rikshawala: Kyuun? Bhabhi hai meri?
Raanjhanaa: Nahi re pagle, paise mai le chukka hoon. Par riksha puncture ho gaya.


31 August 2013

O ‪#‎PMChorHai‬‬ kahne waloon actually ‪#‎MadamChorHai‬‬. Apna PM to bus मुंह ज़ोर hai.


27th August 2013

Between ‪#‎Food4Vote‬‬ and ‪#‎Food4All‬‬ if we take uncommon part, it is 'Vote' 'All'. True picture would come out only if we 'All' 'Vote'.


24th July 2013

Friends kameene hone chahiye, 
Zaroori to phone call bhi hota hai.
‪#‎thought‬‬ ‪


12 June 2013

Boss: Dude can't promote you. Other managers hardly know you. 
Employee: That's because you shut me out of meetings n steal the credit. 
Boss: Keep up the good work. My promotion would help it.


9th June 2013

Yamla Pagla Deewana 2 is Gamla Pheka Purana


26th May 2013

And Fair play award goes to team MumbaiPolice, cleared all towels. ‪#‎IPL‬‬


26th May 2013

Is this IPL final or Final IPL?


13 April 2013


Din, Raat, Weekend kaam kiye to sala kauno naahi poocha. Ek build fail ho gaya to sasura ammrikka takk naam ho gaya hamara. 



20th October 2012

Moral of 'Vadra' N 'Gadkari' story: Capitalism without deniability is same as poverty.


4th August 2012

Doston ki kya kahoon, beshaq kamine the. 
Par raunak unhi se thee, happy friendship day!

16th March 2012

Well well, at least people won't say that #Sachin needed a weak team to reach #100th mark. #IndvsBan #EveryTimeSachin #cricket #AsiaCup


6th March 2012

#Rahul G is blamin Earthquake 4 d results in #UP #Elections2012. Apparantly d EVMs were nt shock proof, votes got shuffled n popped 2 SP


21st Feb 2012

Q: How do you explain 'bhaang' to English Men? 
A: Shiva's Regal! Err... Chivas Regal. #Mahashivratri #omnamahshivay


13th Feb 2012

Ra.One has not only hurt d srk's revenue but spoiled d bollywood's award ceremonies too #recoverloss #overacting #filmfare #zeecine


4th Feb 2012

Abb takk to TeamIndia sirf HARA tha, aaj BESAHARA bhi ho gaya #BCCI #SAHARA


30th January 2012

Good to see #Shirish Kunder's long lived dream being executed, 29 remaining though :~) #TeesMaarKhaan #SRK #SlapGate


15th January 2012

#BCCI cries GoKarting proved ineffective, #TeamIndia 2 try GoFarting @ #Adeleide grounds. Kangaroos mite as well give walkover #AUSvsIND


14th January 2012

Gone Mahi Gone!

Itni shidaat se maine field ki setting ki hai,

ki har balle ne ball boundary paar karane ki saazish ki hai.
Kehte hain ki ...... Agar cricket ko pure dil se chodna chaaho to puri kayanat usi koshish mein lag jaati hai.
Aaj na kal aap sabh mujhe bahar nikalwa hi denge, thank you, thank you very much. Main aap sab ka shukar guzaar hoon.
Ki aapne mere khwabon ko yakeen mein badal diya, itna ki I feel like the Baichung Bhutia of thee Football.
Aur aaj, is baat ka bhi yakeen ho gaya, ki humari filmon ki tarah humare cricket mein bhi end mein sab khatam ho jaata hai.
Happy is Endings. Aur agar, aur agar khatam na ho to koi nahin hai dosto, "Adelaide" abhi baaki hai.


13th January 2012

O koi nahi yaar! Apne ghar kangaroo bhi sher hota hai smile emoticon #AUSvsIND #cricket #waca


13th January 2012

Hence proved, it is a bad idea to play cricket in the middle of go-carting session.


31st December 2011

As #2011 has been the year of soup boyz, pouwa chameli N hud hud dabangg
hope #2012 helps teamanna boyz, Lalu's belly N parliament huddang.


24th December 2011

Software Developer: Can you explain "Good intentions but deadly result"?
Project Manager: Customer wants a cup of tea and you built a system to boil the ocean.


20 December 2011

IT Manager: Do you have all the tool required for your job?
Software Developer: That Depends! Do you consider yourself a tool


8th December 2011

For once I was happy see one Indian demolishing another Indian. I mean by North Indian to West Indian. #sehwag @virendersehwag


8th December 2011

Sachin gets yet another record. Slowest double centurion smile emoticon @virendersehwag @sachin_rt #sehwag


28th August 2011

Anna ne to abhi Ganna dala hai, juice nikalna abhi baki hai mere dost ...


8th July 2011

Kyunki sare Facebookiye bhi kabhi Orkutiye the... #GooglePlus


7th July  2011

-:Dilli Boli:-

Bapu PM se bola, kyu fatati hai teri...

Teri mardangi, property hai teri...

PM ki shakal mein
Beta tu to niklaa kewal daag..
daag... daag...daag..

jaag jaag... jaag jaag...
jaag jaag... jaag jaag...

Oh by GOD phat gayi...
kya se kya huwa
Dekha to thi kursi
Baitha to nikli russi
Madam ke komal haath
Pakda to nikla saaanp... saaanp...saaanp...

jaag jaag M M S jaag jaag M M S jaag jaag
jaag jaag M M S jaag jaag M M S jaag jaag

Tu to hai katputli
Paisa, Kursi aur Dilli
teeno hi
Madam ji se mile.

Tera bheja khali hai...
kyu khata gaali hai...

jaag jaag M M S jaag jaag M M S jaag jaag
jaag jaag M M S jaag jaag M M S jaag jaag


28th June 2011

What's this I heard Anushka Sharma was questioned in the charge of Human Trafficking yesterday. Apparently our very own Bappi Lahri was found in the check-in baggage ...


14th June 2011

Q. Why is Rahul Gandhi absconding amidst so many developments ?
A. Because Child labor in India is a human right issue smile emoticon


21st Feb 2011

Project Manager: You spent whole of engineering budget on learning the new technology. 
Software Developer: Some say I am a slow learner but I'd like to consider myself expensive


11th Feb 2011

Hum to wo hain jo textbooks se bhaga karte the, aur aajkal facebooks me paye jate hain.


11th Oct 2010

While you get your application working 1 way finally. Users would eventually discover n-1 ways where it might not work. And then you call it "Version 1.0"
- Product Line Managment, Software Engineering.


28th September 201o

Rajinikanth doesn’t wear a watch. He decides what time it is.

Friday, 24 July 2015

A letter to my son on his 4th BirthDay.

Dear Aadi,

You turned 4 today. A very very happy birthday :-)

Past one year has been exciting. You are growing from a cute baby to a naughty toddler and I am loving every bit of it. I also got straight 10 months of continuous stay with you without having to move out of station for work. I know you would not remember these early days as you grow. Luck will have it and you may get to relive your childhood when your kid makes his way into the world. Every little mischief you make tells me how was I some 30 years ago. Though I sometimes do feel that I am too calm for all the tantrums you throw and you have significant share of genes from your mom. Yet you two are the best things that has ever occurred to me.

Your fourth year was eventful. Life has a unique communication methodology for its participants. It talks to us via canvases it paints and every move we make in reaction. Some works out and feels good. Some teaches the smarts required to enjoy it the next time. Allow me to redraw the theme of some of the those as I understood it. Perhaps it will prove out to you that life is actually a fun game. We need to play it smartly to win not in the end but during the game.


Your School
Till date you hate the mornings when we dress you up. You hardly smile from the point we wake you till you enter the classroom and sometimes you cry also. Per your class teacher, you are different person in the classroom. You play like there is no tomorrow, scream, run, beat, get beaten. I figured out that its the transition - leaving home and on the way to school, you hate not the school itself. We all have that anxiety. Leaving a comfort zone in anticipation of another comfort zone is a risk and we need to learn to take that calculated risk. These early transitions will make you believe in change and hope that eventually things end well. 

Stage Fear
I still remember the 4 lines I made you by heart on Mars Orbiter and the satellite model that we made for you to wear for school event.  Despite of having practiced for several days at home and in class; you went blank on -the- day. My numerous attempt of cheering from audience and forbearing master of ceremony couldn't get you going. Never mind; it happens.  That day I learnt an important lesson. You never signed up for doing everything right. Kids may fail parent's desire and I better be prepared to work harder the next time. I promise that I won't stop till the day you take the walk up to stage and say ... 'Hello Everyone, I am Adhrit....................'

Leg Fracture
You fractured your left leg in Chicago. I still hear that noise 'kdaak'. Your howl, tears, hospital, plaster all were so painful. We both cried that night. Things do go wrong at times. We must remember that whatever it is we will be past it. And till we are going through it, lets face with hope. Your grand father had told me once ... 'musibat se daro jab wo aane wali ho par jab wo aa hi jaye to himmat rakho aur samna karo. Rolo lekin date raho'. See we are past it. You faced it bravely son. Imagine, you a three year old kid consoling his father ... ' papa, theek ho jayega'

Younger Brother
You are a big bro now. As 'chota' stepped in few months ago. I am sorry that your 'one baby one mom/dad equation was proved wrong' and that I couldn't answer when you asked that where are his mummy/papa and why doesn't he go to his home. I like that you have an audience for the stunts you do and you would repeat those because it makes the baby laugh. Your unique way of caring for him but still not letting him play with your toys. I go to work, mom is busy too at work or making home but you have one special person who has all the time in world for you. You are lucky.


Your Papa.
Mitendra Anand
25th July, 2015

Chicago, USA



Milton Lee Olive Park, Chicago - June 13th 2015









Friday, 25 July 2014

A letter to my son on his 3rd BirthDay.



Dear Aadi,

You turned 3 today, and I still believe that most joyful moment of my life had happened just yesterday. When I was waiting outside of operation theater in hospital and a gentlemen popped after good 40 minutes of wait and said ‘Anushree Anand: I ran….almost fell …. Male Child, Born at 3:42 PM and Body Weight: 3.95 kg’

Your eyes were so wide open and you were looking all around. I couldn’t believe that you were just born, I so wanted to touch you, kiss you but was not granted. ‘Baby needs to be at nursery’ for 24 hours, came the rude voice. I said okay anything for my dear son. I can’t tell you how I felt when I took you in my arms. It seemed pretty technical to say the least, I mean hold in such way that your head is steady still not pressing you hard. All others were scared, and I was like champ without any practice. Of course where else would you be safest if not with me.

Life has changed since. Not very long ago I used to worry about my looks/career/comfort etc. Now whichever store I go, toys fascinates me, baby clothing, shoes are my latest interest. I am kid again and thank God for that and thank you for that.

I know you can’t read it now but one day you shall be. I am writing this letter so that you get a chance to read about your past days because it would feel so different and exciting. I never had this experience so I don’t know how it’d feel, well … will ask you when you are at it. There are few thoughts I would like to share with you on your birthday. These are nothing but some of my wishes which I could not pursue. Now that I have got another life in you I would like to re-do some of that.

Love a sport and pursue it.
As a kid I practiced cricket every day after school. I wasn’t best at it but not bad either. Besides keeping you fit and healthy at mind & body, sport is a wonderful distraction in life. It’s something which gives you every chance to not to think about things which are not in best shape at present. Sport also makes us disciplined in a sense that if you want to get better and then you need to practice certain rules/step on a regular basis. This will make you fighter and force you not to give up easily.

Be a part of musical world.
I am a good listener. I mean that’s the best I could do with music. I suggest you should pick up singing, I know singing is natural talent so one may or one may not but then at least learn to play an instrument. Mankind has always loved the entertainment breed. People who have the ability to sing or play are the core part of the same. They not only de-stress themselves but teach others that world is so beautiful and why not appreciate nature for what it has laid for us. Believe me mother nature did not make us to earn livelihood and break the bread. It had much better plans but we over thought her ideas.

Education is just part of life.
Yes, don’t take it too seriously. I say so because I took it seriously and tried to be best in every subject which was thrown on me . Today I DO NOT earn even a single penny out of those topics for which I burnt midnight oil all my teenage. I wish you better career and prospect than me but I seriously feel that science, mathematics, social science etc would not guarantee that. To be successful I think one just needs to know what he/she is best at and keep refining that. I know people spend 20 years to find one best area for them before they finally succeed. I wish you the same realistically but I want you to remember that ‘studies’ is not necessarily that area so keep your options open. Having said that you must go to school to become educated enough to decide on it.


Your Papa.
Mitendra Anand
25th July, 2014
Chicago, USA

P.S. : Forgive me for not being with you physically, as I said once “Iss do takiye ki naukri me mera lakhon ka bachpan jaye”.



Tuesday, 20 August 2013

Why ChennaiExpress clicked and OnceUponATimeInMumbai D didn't?

Both the movies are hopelessly useless but while  the former clicked the latter didn't. Here is my take on the matter. There were basically 4 aspects of one's failure and others success:- 

Story: ChennaiExpress has the story-line of worst kind. Hero is jobless, purposeless, 40+, can't fight the villain etc. etc. But the good thing with CE, Rohit Shettly was aware of no story. So he put his money on comic timing, fast sreenplay, car actions and colorful canvas. Basically he did not break the pattern, audience got the meal which they were expecting and had tasted before.
OUATMD borrowed its story from Mumbai, so it fairs better. But for stories like underworld you need real incidents so that people can correlate it with past and true picture of purpose not something like running behind love. Broken story is as worse as No Story. Even excellent one liners/ dialogs from Milan Luthria did not help.

Star Cast: Every single viewer is blaiming Imran Khan for OUATMD failure. Rightly so but the fault is not Imran's but the casting crew. Since when we get pink lipped goon? Not a big fan for Sonakshi Sinha either, she was lucky with Dabang her physique suited the character Rajjo, every where else she is a misfit. A lot was on shoulder of Akhsay Kumar and he did deliver in style.
CE has SRK, the biggie himself and Deepika, a better choice any day. 

Music: S P Balasubrahmanyam was a pleasant surprise in CE. The title song justifies the fast screenplay. Then the presence of foot number - 1 2 3 4 Get on the Dance Floor, melody - Titli, Yo Yo - Thalaiva were good addition to the package.
 OUATMD, only song you would remember when out of theatre will be Aiyo Balli ... Pyar ka Dushman. Which is not an original anyway. 

Marketing:  SRK is epitome of marketing products, he has taught bollywood how to do the same. Though he fell on face because of over marketing Ra.One, still looks like it worked this time. Ekta Kapoor should have come with some stepped up marketing for
OUATMD. She believed too much in Akshay's fan following.

Thursday, 15 August 2013

Why Modi scores over Mr. Singh?

As India celebrates it's 67th Independence Day, not sure if India has been really a democracy in the true terms. 1947 onwards, the opposition has had just one full term at the center. The first six decades of its democracy, the center has only seen a government led by a single party. More often than not, power corrupts over a period of time.

Till 80s, India was more successful than China. It was more successful than South Korea, more successful than most places in Asia. It is unfortunate that we have failed to take advantage of some of our most valuable assets. India has some of the smartest people in the world, but it does not have an education system to support it. Infrastructure is equally poor. There are millions of entrepreneurial, driven and smart Indians amongst us, but most of them want to be abroad because they know that unless they are involved with the right people in India, they are not going to be successful. Fewer than 50% of Indians stay in school till they graduate. There are very good Indian universities, but very few for the number of Indians who need good education.

There are not many successful Indian companies either, except those that are associated with the government. Look around in world and you won’t see many Indian products, except for some restaurants. There are very few Indian brands that are recognized outside India. Apart from a couple of software companies, none of the Indian firms have made it big in the international scene. Also, not to forget that the regulations that India puts in place result in foreigners going through nested loops before they can invest in India.

India should have been among the world’s greatest agriculture nations — given the soil, the human resource, the weather, but it is astonishing that we have not become one. It is because Indian politicians, in their wisdom, have made it illegal for farmers to own more than five hectares of land. Can a farmer with just five hectares compete with farmers in Australia or Canada?

As wisely said by Rogers Holdings chairman Jim Rogers , If the billion plus people in India demand more and say the current system that is going on since 1947 is absurd, then it might make India a whole lot better. Compared to many of the countries globally, India was on top in 1947, but relatively India has only declined since then. Remember that you move from dictatorship to oligarchy to democracy to chaos—may be they will throw out these absurd oligarchs who rule India and then it may have a vibrant democracy and regain its proper place, its historic place in the globe. 


आजादी का मतलब - अपने लक्ष्य और अधिकारों के प्रति जागरूक होना |

Monday, 12 August 2013

What C++ has in offer...

Speed: The language not only optimizes in terms of how you program but also makes optimal use of hardware cache. For Example, std::vector gets cached in processor irrespective of its size. Today's Processors come with rich inbuilt cache, let’s make best use of them.

Efficiency: Threading libraries and Parallel/concurrent programming helps in more throughput. In Financial sector the focus is on high demanding applications that need performance. The “king” is Performance per Watt, per Cycle, per Transistor: Performance per Dollar.

C++11: C++11 has a lot of new features. Soon we will use these Features in order to take advantage of new frameworks (like C++ AMP). “C++ matters again as a first class system” i.e. it provides choice at the user level for Windows, Mac OS X and Linux as well as a range of web user interfaces. Imagine the benefit of being able to support the Windows, Mac, and Linux users within your organization with a consistent, identical suite of services.

Alleged Non managed Language: Managed languages don’t have the performance, deployability or serviceability (among others) required to develop a Large Systems or Operating System. That’s why Windows nowadays is all C and C++ and will probably stay that way. The bottom line is that C++ is close to the metal, which means that everything in the execution is right in the code.

Error Proneness: C++ “language” doesn’t provide helpful black box functionality? If there was such a language that could prevent bugs in the software, we wouldn’t be having this discussion.  Everyone would switch.  Fact is, you can write bugs in any language.  When it comes down to the eleventh hour and the problem just has to be solved before I go home that night I need to be able to conveniently walking through every line of code in the debugger.  The so called helpful black box in coder friendly programming languages, that usually works, just becomes a nightmare then.  



In the end choice of language is more like choosing the right size hammer for the nail. For example, if I want to write a device driver for a hardware, I would go for C. If I want to write graphics intensive I would go for C++. If I want to write a new OS I would go for assembly and C. If I want to do text pattern matching and replacement, I would go for Perl/Python. If I want faster web development I would go for Java, PHP. If I want more interactive web page effects, I go for Javascript.

Saturday, 10 August 2013

COM connection point callback for a C++/CLI client

If you have to write interop code, should you use C# and P/Invoke, or should you use C++/CLI? The clients for a COM connection point server can be written in C++ and in C# managed code. Recently, I got a query about the possibility of a managed C++/CLI client for a COM connection point server. A search on the web gave many samples of C++ and C# managed code but none for a C++/CLI client. It is a topic of debate; refer to this blog. It says “With C++/CLI, you can use the API natively exactly like it's meant to be used, and then "expose" the code to the managed world via C++/CLI”. This motivated me to write an article on how to implement a COM connection point callback for a C++/CLI client.

Read More

C++ Interview Questions

Can a member function template be virtual?



Think about it for a while:

Q.1. How could you make a templated virtual function?
Q.2. What's its signature?
Q.3. How many vtable entries do you reserve?
Q.4. How would you distinguish between an override/hide and an overload?


Templates are all about the compiler generating code at compile-time. Virtual functions are all about the run-time system figuring out which function to call at run-time.

Once the run-time system figured out it would need to call a templatized virtual function, compilation is all done and the compiler cannot generate the appropriate instance anymore. Therefor, you cannot have virtual member function templates.

h<int>(&f<int>());


 

Making an API C Callable



A C++ function is not necessarily made C callable by prototyping the C++ function with the extern C keywords. While the extern C keyword prevents the name of the C++ from being mangled, there are other issues to be considered.

C vs C++ Issues

- C does not use classes. Therefore, it cannot pass classes by value. If a C++ API function requires that a class be passed by value as its input, it is not C callable, regardless of whether it is prototyped with the extern C keyword. This leads to the following rule: API functions must not pass classes by value.

- C does have "void pointers". A C void pointer points to the address of a class just as it points to a structure. Therefore, a C++ API function would be C callable if its class arguments were passed by address (BODY*) or by reference (BODY&). Either method allows the API function to be called from C.

 

What is difference between "new operator" and "operator new"?



The difference between the two is that operator new just allocates raw memory, nothing else. The new operator starts by using operator new to allocate memory, but then it invokes the constructor for the right type of object, so the result is a real live object created in that memory. If that object contains any other objects (either embedded or as base classes) those constructors as invoked as well.

Following is the quote from More Effective C++ book from Scott Meyers:

The new operator calls a function to perform the requisite memory allocation, and you can rewrite or overload that function to change its behavior. The name of the function the new operator calls to allocate memory is operator new.

 

Is there any way a C/C++ program can crash before main()?



There are many possibilities.

First, we need to understand what actually goes on before main is executed:

    Load of dynamic libraries
    Initialization of globals
    One some compilers, some functions can be executed explicitly

Now, any of this can cause a crash in several ways:

    the usual undefined behavior (dereferencing null pointer, accessing memory you should not...)
    an exception thrown > since there is no catch, terminate is called and the program end

It's really annoying of course and possibly hard to debug, and that is why you should refrain from executing code before main as much as possible, and prefer lazy initialization if you can, or explicit initialization within main.

Of course, when it's a DLL failing and you can't modify it, you're in for a world of pain.

 

What happens when you run a program?



On Windows, first the image is loaded into memory. The kernel analizes which libraries (read "DLL") it is going to require and loads them up too. Initialization of globals happen.

It then edits the program image to insert the memory addresses of each of the library functions it requires. These addresses have a space in the .EXE binary already, but they are just filled with zeros.

Each DLL's DllMain() procedure then gets executed, one by one, from the most required DLL to the last, like following an order of dependences.

Once all libraries were loaded and got ready, finally the image is started, and whatever happens now will depend on language used, compiler used, and the program routine itself.


Client request to run application
  ->Shell informs kernel to run binary
  ->Kernel allocates memory from the pool to fit the binary image into
  ->Kernel loads binary into memory
  ->Kernel jumps to specific memory address
  ->Kernel starts processing the machine code located at this location
  ->Kernel pops current location into an execution stack
  ->Kernel jumps out of current memory to a shared memory location
  ->Kernel executes code from this shared memory location
  ->Kernel pops back the last memory location and jumps to that address
  ->If machine code has stop
  ->Kernel releases memory back to pool

 

Where does static or non-static variables stay? I mean in memory. and, When are static or non-static variables initialized?



They can go wherever the compiler (or linker or loader) wants to put them in memory, the C and C++ standards don't mandate that level of detail. They only mandate the behaviour.

Typically, static members are initialised once, either on program startup (including at compile time so that they're simply loaded in an already-initialised state) or immediately before first use.

   


 

Difference between WinMain,main and DllMain in C++?



WinMain is used for an application (ending .exe) to indicate the process is starting. It will provide command line arguments for the process and serves as the user code entry point for a process. WinMain (or a different version of main) is also a required function. The OS needs a function to call in order to start a process running.

"DllMain" is used for a DLL to signify a lot of different scenarios. Most notably, it will be called when

    The DLL is loaded into the process: DLL_PROCESS_ATTACH
    The DLL is unloaded from the process: DLL_PROCESS_DETACH
    A thread is started in the process: DLL_THREAD_ATTACH
    A thread is ended in the process: DLL_THREAD_DETACH

DllMain is an optional construct and has a lot of implicit contracts associated with it. For instance, you should not be calling code that will force another DLL to load. In general it's fairly difficult function to get right and should be avoided unless you have a very specific need for it.

This is a good explanation ut it needs to also specify that these are required entry points for the three different types of "executables" (console app, windows app, windows DLL).

A DLL can run directly if you're using "rundll32.exe"

WinMain simply means that there will be NO console window allocated for the app, and its stdin and stdout have nowhere to go. All the guts of Windows API (such as event loop, registration of classes, window creation) still need to be done manually. Also, programs using main() can have windows too.

 

Return value optimization



The following example demonstrates a scenario where the implementation may eliminate one or both of the copies being made, even if the copy constructor has a visible side effect (printing text).[4] The first copy that may be eliminated is the one where C() is copied into the function f's return value. The second copy that may be eliminated is the copy of the temporary object returned by f to obj.

#include <iostream>

struct C {
  C() {}
  C(const C&) { std::cout << "A copy was made.\n"; }
};

C f() {
  return C();
}

int main() {
  std::cout << "Hello World!\n";
  C obj = f();
}

Depending upon the compiler, and that compiler's settings, the resulting program may display any of the following outputs:

Hello World!
A copy was made.
A copy was made.

Hello World!
A copy was made.

Hello World!

Background

Returning an object of builtin type from a function usually carries little to no overhead, since the object typically fits in a CPU register. Returning a larger object of class type may require more expensive copying from one memory location to another. To achieve this, an implementation may create a hidden object in the caller's stack frame, and pass the address of this object to the function. The function's return value is then copied into the hidden object.[5] Thus, code such as this:

struct Data {
  char bytes[16];
};

Data f() {
  Data result = {};
  // generate result
  return result;
}

int main() {
  Data d = f();
}

May generate code equivalent to this:

struct Data {
  char bytes[16];
};

Data * f(Data * _hiddenAddress) {
  Data result = {};
  // copy result into hidden object
  *_hiddenAddress = result;
  return _hiddenAddress;
}

int main() {
  Data _hidden; // create hidden object
  Data d = *f(&_hidden); // copy the result into d
}

which causes the Data object to be copied twice.

In the early stages of the evolution of C++, the language's inability to efficiently return an object of class type from a function was considered a weakness.[6] Around 1991, Walter Bright invented a technique to minimize copying, effectively replacing the hidden object and the named object inside the function with the object used to hold the result:[7]

struct Data {
  char bytes[16];
};

void f(Data *p) {
  // generate result directly in *p
}

int main() {
  Data d;
  f(&d);
}

Bright implemented this optimization in his Zortech C++ compiler.[6] This particular technique was later coined "Named return value optimization", referring to the fact that the copying of a named object is elided.[7]
[edit] Compiler support

Return value optimization is supported on most compilers.[1][8][9] There may be, however, circumstances where the compiler is unable to perform the optimization. One common case is when a function may return different named objects depending on the path of execution:[5][8][10]

#include <string>
std::string f(bool cond = false) {
  std::string first("first");
  std::string second("second");
  // the function may return one of two named objects
  // depending on its argument. RVO might not be applied
  return cond ? first : second;
}

int main() {
  std::string result = f();
}

Threading Building Blocks (Intel® TBB) - Hello World

#include<iostream>
#include"/tbb/mutex.h"
#include"/tbb/tbb_thread.h"
using namespace std;
using namespace tbb;

typedef mutex myMutex;
static myMutex sm;
int i=0;

void someFunction()
{
      myMutex::scoped_lock lock;//create a lock
      
      // Method acquire waits until it can
      // acquire a lock on the mutex
      lock.acquire(sm);     

      //only one thread can access the lines from here...

      /*incrementing i is safe (only one thread 
      can execute the code in this scope) because
      the mutex locked above protects all lines
      of code until the lock release. */
      ++i;

      //simply creating a delay to show that no 
      //other thread can increment i until release()
      //is executed
      sleep(1);

      cout<<"In someFunction "<<i<<endl;
         
      //***...to here***
      lock.release();//releases the lock (duh!)     
}

int main()
{
   //create a thread which executes 'someFunction'

   tbb_thread my_thread1(someFunction);
   tbb_thread my_thread2(someFunction);
   tbb_thread my_thread3(someFunction);

   // This command causes the main thread 
   //(which is the 'calling-thread' in this case)
   // to wait until thread1 completes its task.  
   my_thread1.join();
   my_thread2.join();
   my_thread3.join();
}

Starter Kit - C++11

C++11, also formerly known as C++0x,[1] is the name of the most recent iteration of the C++ programming language, approved by ISO as of 12 August 2011, replacing C++03.[2] The name is derived from the tradition of naming language versions by the year of the specification's publication. Changes from the previous version(C++03) of the standard are listed below.

[Core language runtime performance enhancements]

1. Rvalue references and move constructors

In C++03 (and before), temporaries (termed "rvalues", as they often lie on the right side of an assignment) were intended to never be modifiable — just as in C — and were considered to be indistinguishable from const T& types; nevertheless, in some cases, temporaries could have been modified, a behavior that was even considered to be a useful loophole (for the former, see [5]). C++11 adds a new non-const reference type called an rvalue reference, identified by T&&. This refers to temporaries that are permitted to be modified after they are initialized, for the purpose of allowing "move semantics".

A chronic performance problem with C++03 is the costly and unnecessary deep copies that can happen implicitly when objects are passed by value. To illustrate the issue, consider that a std::vector<T> is, internally, a wrapper around a C-style array with a size. If a std::vector<T> temporary is created or returned from a function, it can be stored only by creating a new std::vector<T> and copying all of the rvalue's data into it. Then the temporary and all its memory is destroyed. (For simplicity, this discussion neglects the return value optimization).

In C++11, a "move constructor" of std::vector<T> that takes an rvalue reference to a std::vector<T> can simply copy the pointer to the internal C-style array out of the rvalue into the new std::vector<T>, then set the pointer inside the rvalue to null. Since the temporary will never again be used, no code will try to access the null pointer, and because the pointer is null, its memory is not deleted when it goes out of scope. Hence, the operation not only forgoes the expense of a deep copy, but is safe and invisible.

Rvalue references can provide performance benefits to existing code without needing to make any changes outside the standard library. The type of the returned value of a function returning a std::vector<T> temporary does not need to be changed explicitly to std::vector<T> && to invoke the move constructor, as temporaries are considered rvalues automatically. (However, if std::vector<T> is a C++03 version without a move constructor, then the copy constructor will be invoked with a const std::vector<T>& as normal, incurring a significant memory allocation.)

For safety reasons, some restrictions are imposed. A named variable will never be considered to be an rvalue even if it is declared as such; in order to get an rvalue, the function template std::move<T>() should be used. Rvalue references can also be modified only under certain circumstances, being intended to be used primarily with move constructors.


2. Generalized constant expressions

int get_five() {return 5;}

int some_value[get_five() + 7]; // Create an array of 12 integers. Ill-formed C++

This was not legal in C++03, because get_five() + 7 is not a constant expression. A C++03 compiler has no way of knowing if get_five() actually is constant at runtime. In theory, this function could affect a global variable, call other non-runtime constant functions, etc.

C++11 introduced the keyword constexpr, which allows the user to guarantee that a function or object constructor is a compile-time constant [6]. The above example can be rewritten as follows:

constexpr int get_five() {return 5;}

int some_value[get_five() + 7]; // Create an array of 12 integers. Legal C++11

This allows the compiler to understand, and verify, that get_five is a compile-time constant.

Prior to C++11, the values of variables could be used in constant expressions only if the variables are declared const, have an initializer which is a constant expression, and are of integral or enumeration type. C++11 removes the restriction that the variables must be of integral or enumeration type if they are defined with the constexpr keyword:

constexpr double acceleration_due_to_gravity = 9.8;
constexpr double moon_gravity = acceleration_due_to_gravity / 6.0;

Such data variables are implicitly const, and must have an initializer which must be a constant expression.



[Core language build time performance enhancements]


1. Extern template

In C++03, the compiler must instantiate a template whenever a fully specified template is encountered in a translation unit. If the template is instantiated with the same types in many translation units, this can dramatically increase compile times. There is no way to prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern data declarations.

C++03 has this syntax to oblige the compiler to instantiate a template:

template class std::vector<MyClass>;

C++11 now provides this syntax:

extern template class std::vector<MyClass>;

which tells the compiler not to instantiate the template in this translation unit.


[Core language usability enhancements]


1. Initializer lists

C++11 binds the concept to a template, called std::initializer_list. This allows constructors and other functions to take initializer-lists as parameters. For example:

class SequenceClass {
public:
    SequenceClass(std::initializer_list<int> list);
};

This allows SequenceClass to be constructed from a sequence of integers, as such:

SequenceClass some_var = {1, 4, 5, 6};

This constructor is a special kind of constructor, called an initializer-list-constructor. Classes with such a constructor are treated specially during uniform initialization (see below)

The class std::initializer_list<> is a first-class C++11 standard library type. However, they can be initially constructed statically by the C++11 compiler only through the use of the {} syntax. The list can be copied once constructed, though this is only a copy-by-reference. An initializer list is constant; its members cannot be changed once the initializer list is created, nor can the data in those members be changed.

Because initializer_list is a real type, it can be used in other places besides class constructors. Regular functions can take typed initializer lists as arguments. For example:

void function_name(std::initializer_list<float> list);

function_name({1.0f, -3.45f, -0.4f});

Standard containers can also be initialized in the following ways:

std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };
std::vector<std::string> v{ "xyzzy", "plugh", "abracadabra" };

 

2. Uniform initialization

C++11 provides a syntax that allows for fully uniform type initialization that works on any object. It expands on the initializer list syntax:

struct BasicStruct {
    int x;
    double y;
};

struct AltStruct {
    AltStruct(int x, double y) : x_{x}, y_{y} {}

private:
    int x_;
    double y_;
};

BasicStruct var1{5, 3.2};
AltStruct var2{2, 4.3};

The initialization of var1 behaves exactly as though it were aggregate-initialization. That is, each data member of an object, in turn, will be copy-initialized with the corresponding value from the initializer-list. Implicit type conversion will be used where necessary. If no conversion exists, or only a narrowing conversion exists, the program is ill-formed. The initialization of var2 invokes the constructor.

One is also able to do the following:

struct IdString {
    std::string name;
    int identifier;
};

IdString get_string()
{
    return {"foo", 42}; //Note the lack of explicit type.
}

Uniform initialization does not replace constructor syntax. There are still times when constructor syntax is required. If a class has an initializer list constructor (TypeName(initializer_list<SomeType>);), then it takes priority over other forms of construction, provided that the initializer list conforms to the sequence constructor's type. The C++11 version of std::vector has an initializer list constructor for its template type. This means that the following code:

std::vector<int> the_vec{4};

will call the initializer list constructor, not the constructor of std::vector that takes a single size parameter and creates the vector with that size. To access the latter constructor, the user will need to use the standard constructor syntax directly.


3. Type Interfaces

C++11 allows to create a variable of the specific type of the initializer:

auto some_strange_callable_type = boost::bind(&some_function, _2, _1, some_object);
auto other_variable = 5;

The type of some_strange_callable_type is simply whatever the particular template function override of boost::bind returns for those particular arguments. This type is easily determined procedurally by the compiler as part of its semantic analysis duties, but is not easy for the user to determine upon inspection.

The type of other_variable is also well-defined, but it is easier for the user to determine. It is an int, which is the same type as the integer literal.

Additionally, the keyword decltype can be used to determine the type of an expression at compile-time. For example:

int some_int;
decltype(some_int) other_integer_variable = 5;

This is more useful in conjunction with auto, since the type of an auto variable is known only to the compiler. However, decltype can also be very useful for expressions in code that makes heavy use of operator overloading and specialized types.

auto is also useful for reducing the verbosity of the code. For instance, instead of writing

for (std::vector<int>::const_iterator itr = myvec.cbegin(); itr != myvec.cend(); ++itr)

the programmer can use the shorter

for (auto itr = myvec.cbegin(); itr != myvec.cend(); ++itr)


4. Range-based for-loop

int my_array[5] = {1, 2, 3, 4, 5};
for (int &x : my_array) {
    x *= 2;
}



5. Lambda functions and expressions

C++11 provides the ability to create anonymous functions, called lambda functions. These are defined as follows:

**********************************
[](int x, int y) { return x + y; }
**********************************

The return type is implicit; it returns the type of the return expression (decltype(x+y)). The return type of a lambda can be omitted so long as all return expressions return the same type.



6. Alternative (template) function syntax

The following, for example, is not allowed in C++03:

template<class Lhs, class Rhs>
  Ret adding_func(const Lhs &lhs, const Rhs &rhs) {return lhs + rhs;} //Ret must be the type of lhs+rhs

The type Ret is whatever the addition of types Lhs and Rhs will produce. Even with the aforementioned C++11 functionality of decltype, this is not possible:

template<class Lhs, class Rhs>
  decltype(lhs+rhs) adding_func(const Lhs &lhs, const Rhs &rhs) {return lhs + rhs;} //Not legal C++11

This is not legal C++ because lhs and rhs have not yet been defined; they will not be valid identifiers until after the parser has parsed the rest of the function prototype.

To work around this, C++11 introduced a new function declaration syntax, with a trailing-return-type:

************************************************************
template<class Lhs, class Rhs>
auto adding_func(const Lhs &lhs, const Rhs &rhs) -> decltype(lhs+rhs) {return lhs + rhs;}
************************************************************
This syntax can be used for more mundane function declarations and definitions:

struct SomeStruct  {
    auto func_name(int x, int y) -> int;
};

auto SomeStruct::func_name(int x, int y) -> int {
    return x + y;
}

The use of the keyword “auto” in this case means something different from its use in automatic type deduction.



7. Object construction improvement

C++11 allows constructors to call other peer constructors (known as delegation). This allows constructors to utilize another constructor's behavior with a minimum of added code. Examples of other languages similar to C++ that provide delegation are Java, C#, and D.

This syntax is as follows:

class SomeType  {
    int number;

public:
    SomeType(int new_number) : number(new_number) {}
    SomeType() : SomeType(42) {}
};

This comes with a caveat: C++03 considers an object to be constructed when its constructor finishes executing, but C++11 considers an object constructed once any constructor finishes execution. Since multiple constructors will be allowed to execute, this will mean that each delegate constructor will be executing on a fully constructed object of its own type. Derived class constructors will execute after all delegation in their base classes is complete.

For base-class constructors, C++11 allows a class to specify that base class constructors will be inherited. This means that the C++11 compiler will generate code to perform the inheritance, the forwarding of the derived class to the base class. Note that this is an all-or-nothing feature; either all of that base class's constructors are forwarded or none of them are. Also, note that there are restrictions for multiple inheritance, such that class constructors cannot be inherited from two classes that use constructors with the same signature. Nor can a constructor in the derived class exist that matches a signature in the inherited base class.

The syntax is as follows:

class BaseClass {
public:
    BaseClass(int value);
};

class DerivedClass : public BaseClass {
public:
    using BaseClass::BaseClass;
};

For member initialization, C++11 allows the following syntax:

class SomeClass {
public:
    SomeClass() {}
    explicit SomeClass(int new_value) : value(new_value) {}

private:
    int value = 5;
};

Any constructor of the class will initialize value with 5, if the constructor does not override the initialization with its own. So the above empty constructor will initialize value as the class definition states, but the constructor that takes an int will initialize it to the given parameter.

It can also use constructor or uniform initialization, instead of the equality initialization shown above.



8. Explicit overrides and final

In C++03, it is possible to accidentally create a new virtual function, when one intended to override a base class function. For example:

struct Base {
    virtual void some_func(float);
};

struct Derived : Base {
    virtual void some_func(int);
};

The Derived::some_func is intended to replace the base class version. But because it has a different interface, it creates a second virtual function. This is a common problem, particularly when a user goes to modify the base class.

C++11 provides syntax to solve this problem.

struct Base {
    virtual void some_func(float);
};

struct Derived : Base {
    virtual void some_func(int) override; // ill-formed because it doesn't override a base class method
};

The override special identifier means that the compiler will check the base class(es) to see if there is a virtual function with this exact signature. And if there is not, the compiler will error out.

C++11 also adds the ability to prevent inheriting from classes or simply preventing overriding methods in derived classes. This is done with the special identifier final. For example:

struct Base1 final { }; ---------------------- IMPORTANT

struct Derived1 : Base1 { }; // ill-formed because the class Base1 has been marked final

struct Base2 {
    virtual void f() final;
};

struct Derived2 : Base2 {
    void f(); // ill-formed because the virtual function Base2::f has been marked final
};

In this example, the virtual void f() final; statement declares a new virtual function, but it also prevents derived classes from overriding it. It also has the effect of preventing derived classes from using that particular function name and parameter combination.

Note that neither override nor final are language keywords. They are technically identifiers; they gain special meaning only when used in those specific contexts. In any other location, they can be valid identifiers.

 

9. Null pointer constant

void foo(char *);
void foo(int);

If NULL is defined as 0 (which is usually the case in C++), the statement foo(NULL); will call foo(int), which is almost certainly not what the programmer intended, and not what a superficial reading of the code suggests.

C++11 corrects this by introducing a new keyword to serve as a distinguished null pointer constant: nullptr. It is of type nullptr_t, which is implicitly convertible and comparable to any pointer type or pointer-to-member type. It is not implicitly convertible or comparable to integral types, except for bool. While the original proposal specified that an rvalue of type nullptr should not be convertible to bool, the core language working group decided that such a conversion would be desirable, for consistency with regular pointer types. The proposed wording changes were unanimously voted into the Working Paper in June 2008.[2]

For backwards compatibility reasons, 0 remains a valid null pointer constant.

char *pc = nullptr;     // OK
int  *pi = nullptr;     // OK
bool   b = nullptr;     // OK. b is false.
int    i = nullptr;     // error ------------------------------- IMPORTANT, this is the idea.

foo(nullptr);           // calls foo(char *), not foo(int);



10. Strongly typed enumerations

In C++03, enumerations are not type-safe. They are effectively integers, even when the enumeration types are distinct. This allows the comparison between two enum values of different enumeration types. The only safety that C++03 provides is that an integer or a value of one enum type does not convert implicitly to another enum type. Additionally, the underlying integral type is implementation-defined; code that depends on the size of the enumeration is therefore non-portable. Lastly, enumeration values are scoped to the enclosing scope. Thus, it is not possible for two separate enumerations to have matching member names.

C++11 allows a special classification of enumeration that has none of these issues. This is expressed using the enum class (enum struct is also accepted as a synonym) declaration:

enum class Enumeration {
    Val1,
    Val2,
    Val3 = 100,
    Val4 // = 101
};

This enumeration is type-safe. Enum class values are not implicitly converted to integers; therefore, they cannot be compared to integers either (the expression Enumeration::Val4 == 101 gives a compiler error).


11. Right angle bracket

C++03's parser defines “>>” as the right shift operator in all cases. However, with nested template declarations, there is a tendency for the programmer to neglect to place a space between the two right angle brackets, thus causing a compiler syntax error.

C++11 improves the specification of the parser so that multiple right angle brackets will be interpreted as closing the template argument list where it is reasonable. This can be overridden by using parentheses:

template<bool Test> class SomeType;
std::vector<SomeType<1>2>> x1;  // Interpreted as a std::vector of SomeType<true> 2>,
// which is not legal syntax. 1 is true.
std::vector<SomeType<(1>2)>> x1;  // Interpreted as std::vector of SomeType<false>,
// which is legal C++11 syntax. (1>2) is false.


[Core language functionality improvements]


1. Variadic templates

Prior to C++11, templates (classes and functions) can only take a fixed number of arguments that have to be specified when a template is first declared. C++11 allows template definitions to take an arbitrary number of arguments of any type.

*****************************************
template<typename... Values> class tuple;
*****************************************

This template class tuple will take any number of typenames as its template parameters:

***************************************************
tuple<int, std::vector<int>, std::map<std::string, std::vector<int>>> some_instance_name;
***************************************************

The number of arguments can be zero, so tuple<> some_instance_name; will work as well.

If one does not want to have a variadic template that takes 0 arguments, then this definition will work as well:

template<typename First, typename... Rest> class tuple;

Variadic templates may also apply to functions, thus not only providing a type-safe add-on to variadic functions (such as printf) - but also allowing a printf-like function to process non-trivial objects.

template<typename... Params> void printf(const std::string &str_format, Params... parameters);

The ... operator has two roles. When it occurs to the left of the name of a parameter, it declares a parameter pack. By using the parameter pack, user can bind zero or more arguments to the variadic template parameters. Parameter packs can also be used for non-type parameters. By contrast, when the ... operator occurs to the right of a template or function call argument, it unpacks the parameter packs into separate arguments, like the args... in the body of printf below. In practice, the use of ... operator in the code causes that the whole expression that precedes the ... operator, will be repeated for every next argument unpacked from the argument pack, and all these expressions will be separated by a comma.

The use of variadic templates is often recursive. The variadic parameters themselves are not readily available to the implementation of a function or class. Therefore, the typical mechanism for defining something like a C++11 variadic printf replacement would be as follows:

void printf(const char *s)
{
    while (*s) {
        if (*s == '%' && *(++s) != '%')
            throw std::runtime_error("invalid format string: missing arguments");
        std::cout << *s++;
    }
}

***********************************************************************************
template<typename T, typename... Args>
void printf(const char *s, T value, Args... args)
{
    while (*s) {
        if (*s == '%' && *(++s) != '%') {
            std::cout << value;
            ++s;
            printf(s, args...); // call even when *s == 0 to detect extra arguments
            return;
        }
        std::cout << *s++;
    }
    throw std::logic_error("extra arguments provided to printf");
}
***********************************************************************************

 

2. Thread-local storage

In a multi-threaded environment, it is common for every thread to have some unique variables. This already happens for the local variables of a function, but it does not happen for global and static variables.

A new thread-local storage duration (in addition to the existing static, dynamic and automatic) is indicated by the storage specifier thread_local.

Any object which could have static storage duration (i.e., lifetime spanning the entire execution of the program) may be given thread-local duration instead. The intent is that like any other static-duration variable, a thread-local object can be initialized using a constructor and destroyed using a destructor.



3. Explicitly defaulted and deleted special member functions

C++11 allows the explicit defaulting and deleting of these special member functions. For example, the following type explicitly declares that it is using the default constructor:

struct SomeType {
    SomeType() = default; //The default constructor is explicitly stated.
    SomeType(OtherType value);
};

Alternatively, certain features can be explicitly disabled. For example, the following type is non-copyable:

struct NonCopyable {
    NonCopyable & operator=(const NonCopyable&) = delete;
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable() = default;
};

The = delete specifier can be used to prohibit calling any function, which can be used to disallow calling a member function with particular parameters. For example:

struct NoInt {
    void f(double i);
    void f(int) = delete;
};

An attempt to call f() with an int will be rejected by the compiler, instead of performing a silent conversion to double. This can be generalized to disallow calling the function with any type other than double as follows:

struct OnlyDouble {
    void f(double d);
    template<class T> void f(T) = delete;
};


4. Type long long int

In C++03, the largest integral type is long int. It is guaranteed to have at least as many usable bits as int. This resulted in long int having size of 64 bits on some popular implementations and 32 bits on others. C++11 adds a new integral type long long int to address this issue. It is guaranteed to be at least as large as a long int, and have no fewer than 64 bits.


5. Static assertions

C++03 provides two methods to test assertions: the macro assert and the preprocessor directive #error. However, neither is appropriate for use in templates: the macro tests the assertion at execution-time, while the preprocessor directive tests the assertion during preprocessing, which happens before instantiation of templates. Neither is appropriate for testing properties that are dependent on template parameters.

The new utility introduces a new way to test assertions at compile-time, using the new keyword static_assert. The declaration assumes the following form:

static_assert (constant-expression, error-message);

Here are some examples of how static_assert can be used:

****************************************************
static_assert ((GREEKPI > 3.14) && (GREEKPI < 3.15), 

"GREEKPI is inaccurate!");
****************************************************

template<class T>
struct Check  {
    static_assert (sizeof(int) <= sizeof(T), "T is not big enough!");
};

Allow sizeof to work on members of classes without an explicit object

In C++03, the sizeof operator can be used on types and objects. But it cannot be used to do the following:

struct SomeType { OtherType member; };

sizeof(SomeType::member); //Does not work with C++03. Okay with C++11


 

6. Threading facilities

While the C++11 language provides a memory model that supports threading, the primary support for actually using threading comes with the C++11 standard library.

A thread class (std::thread) is provided which takes a function object — and an optional series of arguments to pass to it — to run in the new thread. It is possible to cause a thread to halt until another executing thread completes, providing thread joining support through the std::thread::join() member function. Access is provided, where feasible, to the underlying native thread object(s) for platform specific operations by the std::thread::native_handle() member function.

For synchronization between threads, appropriate mutexes (std::mutex, std::recursive_mutex, etc.) and condition variables (std::condition_variable and std::condition_variable_any) are added to the library. These are accessible through RAII locks (std::lock_guard and std::unique_lock) and locking algorithms for easy use.


 

8. Tuple types

Tuples are collections composed of heterogeneous objects of pre-arranged dimensions. A tuple can be considered a generalization of a struct's member variables.

Using variadic templates, the declaration of the tuple class looks as follows:

******************************************************************
template <class ...Types> class tuple;

typedef std::tuple <int , double, string       > tuple_1 t1;
typedef std::tuple <char, short , const char * > tuple_2 t2 ('X', 2, "Hola!");
t1 = t2 ;  // Ok, first two elements can be converted,
           // the third one can be constructed from a 'const char *'.
******************************************************************

Relational operators are available (among tuples with the same number of elements), and two expressions are available to check a tuple’s characteristics (only during compilation):

    std::tuple_size<T>::value returns the number of elements in the tuple T,
    std::tuple_element<I, T>::type returns the type of the object number I of the tuple T.

 

9. Hash tables

The new library has four types of hash tables, differentiated by whether or not they accept elements with the same key (unique keys or equivalent keys), and whether they map each key to an associated value. They correspond to the four existing binary-search-tree-based associative containers, with an unordered_ prefix.

Type of hash table     Associated values     Equivalent keys

std::unordered_set         No         No
std::unordered_multiset     No         Yes
std::unordered_map         Yes         No
std::unordered_multimap     Yes         Yes

New classes fulfill all the requirements of a container class, and have all the methods necessary to access elements: insert, erase, begin, end.

 

10. Regular expressions

The new library, defined in the new header <regex>, is made of a couple of new classes:

    regular expressions are represented by instance of the template class std::regex;
    occurrences are represented by instance of the template class std::match_results.

The function std::regex_search is used for searching, while for ‘search and replace’ the function std::regex_replace is used which returns a new string. The algorithms std::regex_search and std::regex_replace take a regular expression and a string and write the occurrences found in the struct std::match_results.

Here is an example of the use of std::match_results:

const char *reg_esp = "[ ,.\\t\\n;:]";  // List of separator characters.

// this can be done using raw string literals:
// const char *reg_esp = R"([ ,.\t\n;:])";

std::regex rgx(reg_esp);  // 'regex' is an instance of the template class
                      // 'basic_regex' with argument of type 'char'.
std::cmatch match;  // 'cmatch' is an instance of the template class
                // 'match_results' with argument of type 'const char *'.
const char *target = "Unseen University - Ankh-Morpork";

// Identifies all words of 'target' separated by characters of 'reg_esp'.
if( std::regex_search( target, match, rgx ) ) {
    // If words separated by specified characters are present.

    const size_t n = match.size();
    for( size_t a = 0; a < n; a++ ) {
        std::string str( match[a].first, match[a].second );
        std::cout << str << "\n";
    }
}

Note the use of double backslashes, because C++ uses backslash as an escape character. The C++11 raw string feature could be used to avoid the problem.

The library <regex> requires neither alteration of any existing header (though it will use them where appropriate) nor an extension of the core language.

 

11. General-purpose smart pointers

C++11 provides std::unique_ptr, as well as improvements to std::shared_ptr and std::weak_ptr from TR1. std::auto_ptr is deprecated.

 

12. Wrapper reference

A wrapper reference is obtained from an instance of the template class reference_wrapper. Wrapper references are similar to normal references (‘&’) of the C++ language. To obtain a wrapper reference from any object the function template ref is used (for a constant reference cref is used).

Wrapper references are useful above all for function templates, where references to parameters rather than copies are needed:

// This function will obtain a reference to the parameter 'r' and increment it.
void f (int &r)  { r++; }

// Template function.
template<class F, class P> void g (F f, P t)  { f(t); }

int main()
{
    int i = 0 ;
    g (f, i) ;  // 'g<void (int &r), int>' is instantiated
               // then 'i' will not be modified.
    std::cout << i << std::endl;  // Output -> 0

    g (f, std::ref(i));  // 'g<void(int &r),reference_wrapper<int>>' is instantiated
                    // then 'i' will be modified.
    std::cout << i << std::endl;  // Output -> 1
}

 

13. Polymorphic wrappers for function objects

Polymorphic wrappers for function objects are similar to function pointers in semantics and syntax, but are less tightly bound and can indiscriminately refer to anything which can be called (function pointers, member function pointers, or functors) whose arguments are compatible with those of the wrapper.

Through the example it is possible to understand its characteristics:

std::function<int (int, int)> func;  // Wrapper creation using
                                 // template class 'function'.
std::plus<int> add;  // 'plus' is declared as 'template<class T> T plus( T, T ) ;'
                 // then 'add' is type 'int add( int x, int y )'.
func = add;  // OK - Parameters and return types are the same.

int a = func (1, 2);  // NOTE: if the wrapper 'func' does not refer to any function,
                      // the exception 'std::bad_function_call' is thrown.
This new utility was added to the existing <utility> header and didn't need further extensions of the C++ language.

 

 

-----------------

C++11 in nutshell

-----------------


General
    RValue reference and move construct
    constexpr
    initialization list
    auto keyword
        auto as function return type
        auto as iterators
    for loop
        for(int &x: my_array)
    Derived's class constructor can base class constructor
        use base class construtor by using Base::Base
    Override - virtual function
    Final - Disallow class inheritance
    nullptr
    thread_local storage for globals and static
    default - constructor
    delete - copy constructor, operator=
    4 types of hashtables
    regex
        std::regex
        std::match_result   
        std::cmatch instance of std::match_result
        std::regexsearch(target, match, regx)
    unique_ptr IN and auto_ptr OUT
    std::ref to get reference from object
        int i;
        std::ref(i);

Templates
    extern
        to avoid particular type instantiation.
    auto
        template<typename RHS, typename LHS>
        auto funtion_my( RHS r, LHS l) -> decltype(r + l) {return r + l; }
    variadic template
        template <typename... T>
        my_fun(T... t)
    std::tupple
    static_assert