c++ when do you need to go native to c, c with c#? almost never if you are creating a new...
TRANSCRIPT
C++ Scenarios for C# DevelopersEric BattalioSenior Program Manager, Microsoft
C++ScenariosSome slides about C++11More Scenarios
When do you need to go native to C, C with C#? Almost never if you are creating a new application, for which you have control to code every component.
You want to have fun developing againCoding closer to the metal is exciting, challenging, and fun. Expand your mind, pick up the STL, and learn from the C++ community.
SymptomsBored writing the same old codeCurious about what C++ developers see in C++You want to feel the power of the STL and RAIIAttending C++ talks at Tech Ed
ExamplesSuccessfully compiling your first post-Hello World appThat moment you start thinking in STLFollowing the C++ forums on Stack OverflowSpotting and fixing a bug in legacy C++ library
Demo
Hello World (of course)
GotchasTemptation to become template-writing MasterLost time debating when/where to use move/auto/...Stress of recruiters bugging you with C++ jobs
C is pretty easy to learn but C++ is clearly complex. The basics are easy but it takes years to become a master in it (although C++11 is making it a bit easier).
very expert
much ninja
so impresswow!
You may have heard a few things...Forget about 1995C++ is a living languageLanguage tweaks make it easier to do the right thingSpeed is only part of the story; code reuse is vitalVisual Studio is your friend and confidant
Eighty twentyIn C++, a few things done well will get you most of the way to your solution(Or all the way)
Vri
adic
Tem
pla
tes
C+
+ 1
4
Cust
om
allo
cato
rs
Con
tain
ers
an
d
Alg
ori
thm
sR
efe
ren
ces,
Con
sta
nts
an
d R
an
ge-F
or
RTTI
Lam
bda-F
u
Ob
jects
an
d R
AII
Cla
ss intr
icaci
es
Move S
em
anti
cs
Overl
oadin
g n
ew
and d
ele
te
Start with a good book
Good C++ books focus on C++11 and modern C++.
Don’t learn bad habits!
Language EssentialsObjectsRAIIContainers and AlgorithmsReferences, Constants and Range-For
// Thanks to James McNellis!
Language EssentialsObjectsRAIIContainers and AlgorithmsReferences, Constants and Range-For
What is an Object?void f(){ int x{0};}
Copying and Assignmentvoid f(){ int x{0};
int y{x}; // initialize y to be a copy of x y = x; // assign the value of x to y}
Copying and Assignmentclass MyClass { /* ... */ };
void f(){ MyClass x{};
MyClass y{x}; // initialize y to be a copy of x y = x; // assign the value of x to y}
Four Special Operationsvoid f(){ int x{0}; // Construction
int y{x}; // Copy Construction y = x; // Copy Assignment}// y.~int() // Destruction // x.~int()
Four Special Operationsclass MyClass { /* ... */ };
void f(){ MyClass x; // Construction
MyClass y{x}; // Copy Construction y = x; // Copy Assignment}// y.~MyClass() // Destruction // x.~MyClass()
Four Special Operationsclass MyClass{public: MyClass() { puts("Constructing"); } ~MyClass() { puts("Destroying"); } MyClass(MyClass const&) { puts("Copying"); } void operator=(MyClass const&) { puts("Assigning"); }};
Four Special Operationsclass MyClass { /* previously defined */ };
void f(){ MyClass x; // Constructing
MyClass y{x}; // Copying y = x; // Assigning}// y.~MyClass() // Destroying // x.~MyClass() // Destroying
Each object has an addressclass MyClass { /* ... */ };
void f(){ MyClass x;
MyClass* p{&x}; // p is a pointer to x // *p is another name for x}
Different objects have different addresses
void f(){ MyClass x; MyClass y;
// Different objects have different addresses MyClass* px{&x}; // px points to x MyClass* py{&y}; // py points to y assert(px != py);}
Special null pointer valuevoid f(){ MyClass* p{nullptr};}
Pointers are objects toovoid f(){ MyClass x;
MyClass* px1{&x}; MyClass* px2{px1}; assert(px1 == px2);
px1 = nullptr; assert(px1 != px2);}
Indirection is (mostly) implicit in C#// For value types, x and y are distinctint x = 0;int y = x;
y = 42;
// For reference types, x and y refer to the same objectList<int> x = new List<int>();List<int> y = x;
x.Add(1);
Indirection is explicit in C++// x and *p denote the same objectint x{0};int* p{&x};
// Changes the value of x via *p*p = 42;
Indirection is explicit in C++// x and *p denote the same objectMyClass x{};MyClass* p{&x};
// Changes the value of x via *p*p = get_thing();
Lifetime and Storage DurationEach object has a lifetime…from the point at which the object comes into existence (is constructed)…to the point at which the object goes out of existence (is destructed)
Lifetime is associated with storage durationAutomatic storage durationStatic and thread-local storage durationDynamic storage duration
Automatic Storage Durationvoid f(){ MyClass x{}; // Construction
MyClass y{x}; // Copy Construction y = x; // Copy Assignment
}// y.~MyClass() // Destruction // x.~MyClass() // Destruction
Lifetime of y Lifetime of x
Static Storage DurationMyClass x{}; // Global variable
void f(){ static MyClass y{}; // Function-local static variable}
Dynamic Storage Durationvoid f(){ MyClass* p{new MyClass{}};
delete p;}
Lifetime of *p
Dynamic Storage DurationMyClass* f(){ MyClass* p{new MyClass{}}; return p;}
void g(){ MyClass* p{ f() }; delete p;}
Initializationvoid f(){ int a = 0; // Copy initialization int b(0); // Direct initialization int c{0}; // Brace initialization int d{};}
Initializationint global_int; // Zero-initialized
void f(){ int local_int; // Not initialized}
Initializationvoid f(){ int local_int{}; MyClass local_MyClass{};}
Language EssentialsObjectsRAIIContainers and AlgorithmsReferences, Constants and Range-For
RAIIResource Acquisition Is Initialization(Scope-Bound Resource Management)
RAII (Resource Acquisition Is Initialization)
void f(){ MyClass* p{new MyClass{}};
delete p;}
RAII (Resource Acquisition Is Initialization)
void f(){ char* const buffer{new char[1024 * 1024]{}};
// ...use the buffer...
delete[] buffer;}
RAII (Resource Acquisition Is Initialization)
void f(){ char* const buffer{new char[1024 * 1024]{}};
// ... throw std::runtime_error{"oops“}; // ...
delete[] buffer;}
RAII (Resource Acquisition Is Initialization)
void f(){ char* const buffer{new char[1024 * 1024]{}};
// ... return; // ...
delete[] buffer;}
RAII (Resource Acquisition Is Initialization)
void f(){ // Not actual C++ char* const buffer{new char[1024 * 1024]{}}; try { // ...use the buffer... } finally { delete[] buffer; }}
RAII (Resource Acquisition Is Initialization)
void f(){ // Not actual C++ using (char* const buffer{new char[1024 * 1024]{}}) { // ...use the buffer... }}
RAII (Resource Acquisition is Initialization)
void f(){ scoped_buffer buffer{new char[1024 * 1024]{}};
// ...use the buffer...
}// buffer.~scoped_buffer()
RAII (Resource Acquisition is Initialization)
struct scoped_buffer{public: scoped_buffer(char* const p) : _p{p} { } ~scoped_buffer() { delete[] _p; } char* get() const { return _p; }
private: scoped_buffer(scoped_buffer const&) = delete; void operator=(scoped_buffer const&) = delete;
char* _p;};
RAII (Resource Acquisition is Initialization)void f(){ scoped_buffer buffer{new char[1024 * 1024]{}};
// ...use the buffer...
}// buffer.~scoped_buffer()
RAII (Resource Acquisition is Initialization)
void f(size_t const buffer_size){ std::unique_ptr<char[]> const buffer{new char[buffer_size]{}};
// ...code that uses the buffer...}
RAII (Resource Acquisition is Initialization)
std::unique_ptr<char[]> f(size_t const buffer_size){ std::unique_ptr<char[]> buffer{new char[buffer_size]{}};
return buffer;}
C++ Rule #1Never use delete in your codeAlways use a smart pointer to manage dynamic lifetimesunique_ptr, shared_ptr, ComPtr, etc.
RAII (Resource Acquisition is Initialization)
std::mutex _sync;
void f(){ _sync.lock();
// ...synchronized code...
_sync.unlock();}
RAII (Resource Acquisition is Initialization)
void f(){ std::unique_lock<std::mutex> lock(_sync);
// ...synchronized code...}
RAII (Resource Acquisition is Initialization)
void f(char const* const file_name){ FILE* file(fopen(file_name, "r"));
// ...code that uses the file...
fclose(file);}
RAII (Resource Acquisition is Initialization)
void f(char const* const file_name){ std::ifstream file(file_name);
// ...code that uses the file...}
C++ Rule #1 (Revised)Never manage resources manually in your C++ codeAlways use RAII container typesUse existing RAII container types where possibleWrite your own when necessary
Language EssentialsObjectsRAIIContainers and AlgorithmsReferences, Constants and Range-For
Containers and Algorithmsstd::vectorstd::liststd::setstd::mapstd::unordered_setstd::unordered_map
ListLinkedListSortedSetSortedDictionaryHashSetDictionary
Containers and Algorithmsstd::vector::insertstd::vector::push_backstd::vector::erasestd::vector::clear
List.InsertList.AddList.RemoveAtList.Clear
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };
for (size_t i{0}; i != v.size(); ++i){ std::cout << v[i] << '\n';}
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };
for (auto it{v.begin()}; it != v.end(); ++it) // std::vector<int>::iterator{ std::cout << *it << '\n';}
Containers and Algorithmsstd::set<int> s{ 1, 2, 3, 4, 5, 6 };
for (auto it{s.begin()}; it != s.end(); ++it) // std::vector<int>::iterator not now!{ std::cout << *it << '\n';}
Containers and Algorithmsstd::map<int, int> m{ { 1, 2 }, { 2, 4 }, { 3, 6 }, { 4, 8 }, { 5, 10 }, { 6, 12 }};
for (auto it{m.begin()}; it != m.end(); ++it){ std::cout << it->first << ': ' << it->second << '\n';}
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };
for (auto it{v.begin()}; it != v.begin() + 3; ++it){ std::cout << *it << '\n';}
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };
v.erase(v.begin() + 3); // Removes the 4v.insert(v.begin() + 2, 10); // Inserts a 10 after the 2
int const x{*(v.begin() + 1)}; // Gets the 2
*(v.begin() + 1) = 9; // Changes the 2 to a 9
int const y{*(v.begin() + 1000)}; // Invalid!
Containers and AlgorithmsOkay, what about operations like sort and find?
v.sort(); // Nope; doesn't existv.find(4); // Nope; doesn't exist
Containers and Algorithms
Iterators
Containers
Algorithms
Containers and Algorithmsstd::vector<int> v{ 1, 3, 5, 2, 4, 6 };
std::sort(v.begin(), v.end());
Containers and Algorithmsstd::vector<int> v{ 1, 3, 5, 2, 4, 6 };
auto const it{std::find(v.begin(), v.end(), 2)};if (it != v.end()){ std::cout << "I found a two!\n";}
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };
if (std::binary_search(v.begin(), v.end(), 2)){ std::cout << "I found a two!\n";}
Containers and Algorithmsfor_eachtransformall_ofany_offindFind_if
binary_searchlower_boundupper_boundequal_rangesortstable_sort
copy_ifuniquepartitionremoverotateand many more…
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };
std::for_each(v.begin(), v.end(), [](int const x){ std::cout << x << '\n';})
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };
std::transform(v.begin(), v.end(), v.begin(), [](int const x){ return x * x;});
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };std::vector<int> w(v.size());
std::transform(v.begin(), v.end(), w.begin(), [](int const x){ return x * x;});
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };std::vector<int> w;
std::transform(v.begin(), v.end(), std::back_inserter(w), [](int const x){ return x * x;});
Containers and Algorithmsstd::vector<int> v{ 1, 3, 5, 2, 4, 6 };
std::sort(v.begin(), v.end(), [](int const lhs, int const rhs){ return lhs > rhs;});
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };
bool const all_are_even(std::all_of(v.begin(), v.end(), [](int const x){ return x % 2 == 0;}));
Containers and Algorithmsstd::vector<int> v{ 1, 2, 3, 4, 5, 6 };
std::set<int> s(v.begin(), v.end());
Containers and Algorithmsint a[6]{ 1, 3, 5, 2, 4, 6 };
std::sort(begin(a), end(a));
Containers and Algorithmsvoid f(int* const data, size_t const count){ int* const first{data}; int* const last {data + count};
std::sort(first, last);}
Containers and Algorithmstemplate <typename Iterator, typename Function>bool all_of(Iterator const first, Iterator const last, Function const f){ for (Iterator it{first}; it != last; ++it) { if (!f(*it)) return false; }
return true;}
Language EssentialsObjectsRAIIContainers and AlgorithmsReferences, Constants and Range-For
Referencesvoid f(){ int x{0}; // x is an object
int& rx{x}; // rx is a reference to x // it is another name for x}
Referencesvoid f(std::vector<int>& v){ // ...Use the vector...}
constvoid f(){ int const x{0}; x = 42; // Invalid; x is const}
constvoid f(){ int x(0);
int const& rx(x); int const* px(&x);
x = 42; // Ok, x is not const rx = 42; // Invalid; rx is const *px = 42; // Invalid; *px is const}
constvoid f(std::vector<int> const& v){ // ...Use the vector but don't modify it...}
Range-forvoid f(){ std::vector<int> v = { 1, 2, 3, 4 };
for (const auto& x : v) { std::cout << x << '\n'; }}
autostd::vector<int> get_stuff();
void f(){ auto the_stuff = get_stuff();}
I was once on a project where performance was important, so the core of the program was written in C++. Other people would use it on different platforms including Unix and Linux.
You need portable codeWhen it comes to portable code, C++ is hard to beat. It is build on a rich heritage of compatibility.There are differences among compilers, but all provide a reasonable ISO C++ standard compliant experience.
ScenarioCode needs to perform well on multiple devicesCode needs to be accessible on multiple devices
SymptomsYou need features only accessible to native codePerformance concerns for managed language
Examples<pattern: hamburger, UI layer on top, device API on bottom, meat is the C++ portable layer>
Demo
Portable Code
GotchasSource and build management complexityConformance differences
I also use C++ when I need to access some specific features from CryptoAPI or create high performance stuff web server stuff.
If you are planning to develop a math intensive library such as a quant library, stochastic analysis, signal processing or alike, go with C++.
You need to tune a managed applicationC# performs admirably across a range of applications.But!Sometimes application hot spots drive down performance and cannot be solved in native code alone.
SymptomsProfiler exposes code that has already been optimizedCustom graphics UI is sluggishExcessive amounts of data marshalling
ExamplesCrunching large amounts of data (image, audio)Excessive amounts of data marshallingLarge file processingComplex algorithms (financial, data structures)
Demo
C++ AMP
GotchasPremature optimizationTradeoffs (simplicity/maintainability for complexity)Missed or unforeseen causes (constrained by db)Installation and deployment
I also use C++ when I need to access some specific features from CryptoAPI or create high performance stuff web server stuff.
If you are planning to develop a math intensive library such as a quant library, stochastic analysis, signal processing or alike, go with C++.
Talking to older systemsOld systems never seem to die. Insurance, engineering, manufacturing, medical – many industries run on older applications. Submitting a claim or new part order may require specialized protocols.
SymptomsCompany has a place you go to request tape loadsBusiness rules are a “black box”Reliance on bridging middleware
ExamplesHealth care claims processing and adjudicationEngineering modelling Chemical processing and schedulingHome-grown, stove-pipe systemsJob systems
GotchasAPIs might be brittle...and pickyPerformance mismatchError handling (return codes)
You need to use existing code librariesCritical functionality vital to your project exist only in native C/C++ libraries.
SymptomsSchedule or other pressures make rewrite impossibleSource is inaccessible and/or surrounded by folkloreFeature is already implemented in OSS libraryExisting code is compliant/certified/secureCustom hardware control
ExamplesEDI transmission componentData cryptography servicesComputer visionAssembly line product quality hardwarePhysics, graphics, or other niche
Demo
Consuming and extending APIs
GotchasDependency on external development resourcesToo many cross-boundary callsData conversions (ascii / MBCS / Unicode / platform string...)Memory leaks, null pointers, security vulnerabilities
Thank YouPing me any [email protected]
Follow Visual C++ Team Bloghttp://blogs.msdn.com/b/vcblog/
We want your suggestions, help us improve Visual Studio and Visual C++Visit Visual C++ on User Voice http://aka.ms/UserVoiceVisualCPP
Favorite Things for C++ Developers in Visual Studio 2013, DEV-B223
Debugging Tips and Tricks in Visual Studio 2013, DEV-B352
Related content
What's New in Microsoft Visual Studio 2013 for C++ Developers, DEV-H223
Find me later in the Visual Studio booth, on Twitter @visualc or at [email protected]
Resource 1
Track resources
Resource 2
Resource 3
Resource 4
Required Slide*delete this box when your slide is finalized
The PMs will supply the content for this slide, which will be inserted during the final scrub.
Resources
Learning
Microsoft Certification & Training Resources
www.microsoft.com/learning
msdn
Resources for Developers
http://microsoft.com/msdn
TechNet
Resources for IT Professionals
http://microsoft.com/technet
Sessions on Demand
http://channel9.msdn.com/Events/TechEd
Complete an evaluation and enter to win!
Evaluate this session
Scan this QR code to evaluate this session.
© 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.