Upload
paul-irwin
View
263
Download
2
Embed Size (px)
DESCRIPTION
What's new with C++ since, oh, before the dot-com bubble? Learn more in this Lunch and Learn, with a refresher of C++ basics, C++/CLI for C# developers, and the new features of C++11/14 and possibly C++17.
Citation preview
Modern C++Lunch and Learn From an Amateur
By Paul Irwin
Ancient History
• C created by Dennis Ritchie, 1972 [9]
• “C with Classes” created by Bjarne Stroustrup, 1979 [9]
• Renamed to C++, 1983 [9]
• The C++ Programming Language, 1985 [9]
• The C++ Programming Language 2nd Ed. and C++ 2.0, 1989 [9]
• ISO Standardization as C++98, 1998 [9]
• Minor ISO revision in C++03, 2003 [9,4]
C++ is “C with Classes”
• Often, C can be used in C++ [1]
• C is fast, portable, and versatile [1]• Therefore so is C++
• C has only structs to define composite types• Passed by-value unless with a pointer• No inheritance, polymorphism, encapsulation• So not object-oriented
• C++ adds classes that bring OO to C
• But, knowing C is not a prerequisite for learning C++ [1]
C++ invalidates some C approaches
• Macros are almost never necessary [1]
• Don’t use malloc() [1]
• Avoid void*, pointer arithmetic, unions, and casts [1]
• Minimize use of arrays and C-style strings [1]
• C does not provide a native Boolean type [2]
When Should I C++?
• For Performance• Raw algorithms• C++/CLI code called from C#
• For Interop• Got a native lib on your hands? Create a C++/CLI interop DLL.
• For Portability• C++ can run on just about any device, any platform, any CPU that matters
• For Resource Optimization• With nearly identical simple demo apps in C++ and C#, C++ used ~90% less memory
• Instant memory cleanup – all objects are “IDisposable“ [4]• Important for embedded devices, mobile, certain server applications
C-style Code
Problems:• What if string is > 99 chars?• What if \0 is in middle of string?• What if char* is dangerous?• What if you forget to null-terminate?
C++ Standard Library std::string
• Anytime you see “using namespace std” or “std::”,that is the C++ standard library
• #include <string>
C++ Classes Primer
C# developers go “HOLD ON A DAMN SECOND!”
“Where’s the new keyword?”
Stack vs Heap
• Person p(123, “Paul”);• Calls ctor Person(int id, string name)• Allocates on local function stack• No pointer!• Destroyed at end of scope – no memory management! – thanks “}”
• Person* p = new Person(123, “Paul”);• Calls ctor Person(int id, string name)• Allocates on free heap space• Notice that little asterisk (grumble grumble)• Yes, it’s a damn pointer.• Not destroyed at end of scope – whoops, memory leak!• Remember: C++ does not have garbage collection!• We’ll come back to this…
.NET vs C++
• .NET Struct ~== C++ class on stack• C#: var kvp = new KeyValuePair<int, string>(123, “Paul”);• C++: KeyValuePair<int, string> kvp(123, “Paul”);
• .NET Class ~== C++ class on heap• C#: Person p = new Person(123, “Paul”);• C++: Person* p = new Person(123, “Paul”);
• .NET Interface ~== C++ … well …• Pure virtual functions (virtual void foo() = 0;)• Macros• Non-Virtual-Interfaces (NVI)• … and down the rabbit hole you go
Pointer Primer
C++ Templates Primer
• vector<int> better than int[]
• Looks like a generic type – kinda is, kinda isn’t
• Created at compile time
C++/CLI Primer
Notice:• CLR namespaces like C++ namespaces• ^ means CLR type• gcnew means allocate in CLR heap,
garbage collected (hence “gc”)• C-style string to String^• -> operator for dereference call:
rx is a .NET reference type• :: scope operator for static
instances/methods
C++/CLI Primer: Classes
Notice:• ref keyword means CLR type• No need for Int32^• property keyword for CLR properties• Mix-and-match C++/CLI and C++
Modern History
• After C++03…
• C++0x draft – expected to be released before 2010
• C++0x -> C++11 – a wee bit late• First major release of C++ since C++98 – 13 years!
• C++14 Working Draft• Minor release, 3 year cadence [4]
• C++17 (expected)• Next major release, 3 year cadence [4]
C++11: move semantics
• Prior to C++11, this code could result in a deep copy of v• v is created on the stack
• We fill v with values
• “return v” copies all values into v2 when called – O(n)
• C++11 now implicitly “moves” v into v2• Much better performance, esp. with large objects – O(1)
• Further reading: std::move [3]
C++11: initializer lists
• From previous slide, now we can do this instead• Calls ctor on vector<int> taking initializer_list<int>
• You can return objects this way too [3]• Neat! But may still want ctors
• You can write methods that take initializer_list<T> [3]
C++11: type inference
• “var” spelled “auto” [4]
C++11: range-based for loop
• Makes the previous slide look bad
C++11: lambda functions (!!!)
• YAY
So this clearly prints even numbers to the console. And actually, you really should be using range-based for here.But what’s up with that [] syntax?
C++11: lambda functions (cont’d)
• [](int x) { return x + 1; }• Captures no closures [5]
• [y](int x) { return x + y; }• Captures y by value (copy) [5]
• [&](int x) { y += x; }• Capture any referenced variable (y here) by reference [5]
• [=](int x) { return x + y; }• Capture any referenced variable (y here) by value (copy) [5]
• [=, &y](int x) { y += x + z; }• Capture any referenced variable (z here) by value (copy); but capture y by reference [5]
• [this](int x) { return x + _privateFieldY; }• Capture the “this” pointer in the scope of the lambda [5]
C++11: lambda functions (cont’d)
C++11: strongly typed enums
• In C++03, enums are not type safe [6]
• C++11 adds “enum class” for type safety [3]
C++11: std::thread
C++11: std::tuple
C++11: std::regex
C++11: shared_ptr, unique_ptr
• Consider: Person* GetPerson() { … }
• What should be done with the results? [7]• Who owns the pointer?
• If I “delete” it, what will happen downstream?
• Enter std::shared_ptr and std::unique_ptr [7]• shared_ptr: reference-counted ownership of pointer
• unique_ptr: only one unique_ptr object can own at a given time
• unique_ptr deprecates auto_ptr
C++11: std::make_shared
• Forwards arguments to constructor parameters
Notice:• Return types and parameter types
are explicit and clear• -> still used like with raw
pointers• NO DAMN ASTERISKS!• When DealWithPersons’ scope ends
(“}”), no more references, so pointer is cleaned up automatically
• Could also call “return shared_ptr<Person>(new Person(…))” in MakePerson
C++14: std::make_unique
• Oops! std::make_unique was not in the C++11 standard.
• Same usage as make_shared, supported in VS2013
C++14: return type deduction
C++14: binary literals
• 0b10010010
• Also coming to C#!
C++14: generic lambdas
• Use auto to make a generic lambda [8]
C++17?: pattern matching
int eval(Expr& e) // expression evaluator
{
Expr* a,*b;
int n;
match (e)
{
case (C<Value>(n)): return n;
case (C<Plus>(a,b)): return eval(*a) + eval(*b);
case (C<Minus>(a,b)): return eval(*a) - eval(*b);
case (C<Times>(a,b)): return eval(*a) * eval(*b);
case (C<Divide>(a,b)): return eval(*a) / eval(*b);
}
}
// From [10], possible syntax mine (not indicative of any proposed syntax I’ve seen)
C++17?: async/await
future<void> f(stream str) async
{
shared_ptr<vector> buf = ...;
int count = await str.read(512, buf);
return count + 11;
}
future g() async
{
stream s = ...;
int pls11 = await f(s);
s.close();
}
// Code from [11]
Notice:• future<T> equivalent to Task<T>• async/await very similar to C#• std::future already in the
standard since C++11!
C++17?: modules
// File_1.cpp:
export Lib:
import std;
using namespace std;
public:
namespace N {
struct S {
S() {
cout << “S()\n”;
}
};
}
// File_2.cpp:
import Lib; // no guard needed
int main() {
N::S s;
}
// Code modified from [12]
References
1. The C++ Programming Language, Special Edition, B. Stroustrup, 1997
2. Differences Between C and C++, http://www.cprogramming.com/tutorial/c-vs-c++.html
3. C++11, http://en.wikipedia.org/wiki/C%2B%2B11
4. Modern C++: What You Need To Know [Video], http://channel9.msdn.com/Events/Build/2014/2-661
5. C++11 – Lambda Closures, The Definitive Guide, http://www.cprogramming.com/c++11/c++11-lambda-closures.html
6. C++ Enumeration Declarations, http://msdn.microsoft.com/en-us/library/2dzy4k6e.aspx
7. Smart Pointers, http://en.wikipedia.org/wiki/Smart_pointer
8. C++14, http://en.wikipedia.org/wiki/C%2B%2B14
9. C++, http://en.wikipedia.org/wiki/C%2B%2B
10. C++14 and early thoughts about C++17 [Slides PDF], B. Stroutstrup, https://parasol.tamu.edu/people/bs/622-GP/C++14TAMU.pdf
11. Resumable Functions – Async and await – Meeting C++, http://meetingcpp.com/index.php/br/items/resumable-functions-async-and-await.html
12. Modules in C++, D. Vandevoorde, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2316.pdf