What's new in Microsoft Visual C Preview

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick The Programming Process rUse an editor to create a program file (source file). l contains the text of.
Advertisements

Brown Bag #3 Return of the C++. Topics  Common C++ “Gotchas”  Polymorphism  Best Practices  Useful Titbits.
Overview  Miscellaneous Utility Functions  Return Type Deduction  Generic Lambdas  Generalised Lambda Captures  C++14 Literals  constexpr Functions.
Writing Modern C++ Marc Grégoire Software Architect April 3 rd 2012.
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
C++ Basics Variables, Identifiers, Assignments, Input/Output.
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 192 Lecture 3 Winter 2003 December 5, 2003 Dr. Shafay Shamail.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
Copyright © 2002 W. A. Tucker1 Chapter 7 Lecture Notes Bill Tucker Austin Community College COSC 1315.
C Tokens Identifiers Keywords Constants Operators Special symbols.
C-Language Keywords(C99)
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
Looping and Counting Lecture 3 Hartmut Kaiser
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Introduction to Programming
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
C++ Basics Tutorial 5 Constants. Topics Covered Literal Constants Defined Constants Declared Constants.
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
LECTURE LECTURE 14 Exception Handling Textbook p
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
Basic Types, Variables, Literals, Constants. What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet)
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 15 - C++ As A "Better C"
C++ Lesson 1.
Asst.Prof.Dr. Tayfun ÖZGÜR
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Data types Data types Basic types
Why exception handling in C++?
Instructor: Ioannis A. Vetsikas
Reserved Words.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
2.1 Parts of a C++ Program.
An overview of Java, Data types and variables
Built-In (a.k.a. Native) Types in C++
Variables, Identifiers, Assignments, Input/Output
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
Prof. Bhushan Trivedi Director GLS Institute of Computer Technology
Chapter 2: Introduction to C++.
C++ Programming Lecture 3 C++ Basics – Part I
2. Second Step for Learning C++ Programming • Data Type • Char • Float
ECE 103 Engineering Programming Chapter 8 Data Types and Constants
Programming Language C Language.
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

What's new in Microsoft Visual C++ 2015 Preview Marc Grégoire marc.gregoire@nuonsoft.com http://www.nuonsoft.com/ http://www.nuonsoft.com/blog/ December 17th 2014

Agenda C++11, C++14, C++17 Productivity Improvements Improved Performance C++ Cross-Platform Mobile Dev

C++11, C++14, C++17 Increased standard compliancy

C++11 Core Language Features New or updated C++11 core language features ref-qualifiers Partial support for constexpr Inheriting constructors char16_t and char32_t Unicode string literals User-defined literals Full defaulted and deleted functions support (partial in VC++2013) Extended sizeof() noexcept Inline namespaces Full Rvalue references compliant (partial VC++2013) Full alignment support (partial in VC++2013) Unrestricted unions Italic features not further discussed.

ref-qualifiers rvalue references are well-known for function parameters, example: void foo(Bar&& bar); How to apply rvalue reference to *this? class Foo { void f1() const; // *this is const void f2() &; // *this is an lvalue void f3() &&; // *this is an rvalue };

ref-qualifiers – Contrived Example class BigObject {}; class BigObjectFactory { public: BigObject Get() { return m_bigObject; } private: BigObject m_bigObject; }; BigObjectFactory aFactory; BigObject obj = aFactory.Get();

ref-qualifiers – Contrived Example But what with this: BigObject obj = BigObjectFactory().Get(); The factory is a temporary object, but BigObject is still copied because *this is not an rvalue-reference Solution: Make BigObject moveable Overload Get() for an rvalue-reference *this

ref-qualifiers – Contrived Example class BigObject {}; class BigObjectFactory { public: BigObject Get() const & { // *this is an lvalue return m_bigObject; // Deep copy } BigObject Get() && { // *this is an rvalue return std::move(m_bigObject); // move private: BigObject m_bigObject; }; BigObjectFactory myFactory; BigObject o1 = myFactory.Get(); // Deep copy BigObject o2 = BigObjectFactory().Get();// Move

constexpr Constant expressions Simple example static constexpr size_t FACTOR = 2; constexpr size_t CalculateArraySize(size_t base) { return base * FACTOR; } ... double arr[CalculateArraySize(123)];

Inheriting constructors class Base { public: Base(int data) : m_data(data) {} private: int m_data; }; class Derived : Base Derived(const std::string& msg) : Base(1), m_msg(msg) {} std::string m_msg; ... Base b1(123); // OK Derived d1("Message"); // OK Derived d2(456); // NOT OK

Inheriting Constructors class Base { public: Base(int data) : m_data(data) {} private: int m_data; }; class Derived : Base using Base::Base; Derived(const std::string& msg) : Base(1), m_msg(msg) {} std::string m_msg; ... Derived d2(456); // OK

char16_t and char32_t Existing character types: char: only 8 bits wchar_t: compiler-dependent size, not specified by C++ standard!  hard to use for platform independent code New character types: char16_t and char32_t On Windows wchar_t is 16 bits, while on other platforms it could be 32 bits.

char16_t and char32_t In total 4 character types: char: stores 8 bits; can be used to store ASCII, or as building block for UTF-8 encoded Unicode characters char16_t: stores at least 16 bits; building block for UTF- 16 encoded Unicode characters char32_t: stores at least 32 bits; building block for UTF- 32 encoded Unicode characters wchar_t: stores a wide character of a compiler dependent size and encoding

char16_t and char32_t A compiler can define the following new preprocessor defines: __STDC_UTF_32__: If defined then char32_t represents a UTF-32 encoding, otherwise it has a compiler dependent encoding. __STDC_UTF_16__: If defined then char16_t represents a UTF-16 encoding, otherwise it has a compiler dependent encoding. Both not defined in VC++2015 Preview

char16_t and char32_t New std::basic_string specializations: typedef basic_string<char> string; typedef basic_string<wchar_t> wstring; typedef basic_string<char16_t> u16string; typedef basic_string<char32_t> u32string;

char16_t and char32_t Unfortunately, support for char16_t and char32_t stops here No I/O stream classes support these new types No version of cout/cin/… for these types

Unicode String Literals New string literals: L: A wchar_t string literal with a compiler-dependent encoding u8: A char string literal with UTF-8 encoding u: A char16_t string literal, which can be UTF-16 if __STDC_UTF_16__ is defined by the compiler U: A char32_t string literal, which can be UTF-32 if __STDC_UTF_32__ is defined by the compiler

Unicode String Literals All can be combined with the R prefix for raw string literals: const char* s1 = u8R"(Raw UTF-8 encoded string literal)"; const wchar_t* s2 = LR"(Raw wide string literal)"; const char16_t* s3 = uR"(Raw char16_t string literal)"; const char32_t* s4 = UR"(Raw char32_t string literal)";

User-Defined Literals C++ has standard literals such as: 'a': character "character array": zero-terminated array of characters, C-style string 3.14f: float floating point value 0xabc: hexadecimal value

User-Defined Literals Start with _ Implemented in a literal operator: Raw mode: op receives sequence of characters Cooked mode: op receives an interpreted type Example: literal 0x23 Raw mode op receives ‘0’, ‘x’, ‘2’, ‘3’ Cooked mode op receives the integer 35

User-Defined Literals – Cooked Mode Has 1 parameter to process numeric values Type can be unsigned long long, long double, char, wchar_t, char16_t or char32_t or 2 parameters to process strings a character array the length of the character array example: (const char* str, size_t len)

User-Defined Literals – Cooked Mode Example: cooked mode complex number literal std::complex<double> operator"" _i(long double d) { return std::complex<double>(0, d); } std::complex<double> c1 = 9.634_i; auto c2 = 1.23_i; // type is std::complex<double> Just an example. C++14 has standard UDLs for complex number literals.

User-Defined Literals – Cooked Mode Example: cooked mode std::string literal std::string operator"" _s(const char* str, size_t len) { return std::string(str, len); } std::string str1 = "Hello World"_s; auto str2 = "Hello World"_s; // type is std::string auto str3 = "Hello World"; // type is const char* Just an example. C++14 has standard UDLs for std::string literals.

User-Defined Literals – Raw Mode Example: raw mode complex number literal std::complex<double> operator"" _i(const char* p) { // Implementation omitted; it requires parsing the C-style // string and converting it to a complex number. } Just an example. C++14 has standard UDLs for complex number literals.

Full Defaulted and Deleted Functions Support Ask the compiler to forcefully generate the default implementation Example: class C { public: C(int i) {} C() = default; };

Full Defaulted and Deleted Functions Support Forcefully delete an implementation Error message states intent, better error message than making it private without implementation Example: class C { public: C() = delete; C(const C& src) = delete; C& operator=(const C& src) = delete; }; C c;//error C2280:'C::C(void)': attempting to reference a deleted function

Full Defaulted and Deleted Functions Support =delete can be used to disallow calling a function with a certain type Example: void foo(int i) { } ... foo(123); foo(1.23); // Compiles, but with warning Disallow calling foo() with doubles by deleting a double overload of foo(): void foo(double d) = delete; foo(1.23); // error C2280: 'void foo(double)' : // attempting to reference a deleted function

Extended sizeof() sizeof() on class members without an instance Example: class Bar {}; class Foo { public: Bar m_bar; }; sizeof(Foo::m_bar);

noexcept Double meaning: noexcept to mark a function as non-throwing void func1(); // Can throw anything void func2() noexcept(expr); // A constant expression returning a Boolean // true means func2 cannot throw // false means func2 can throw void func3() noexcept; // = noexcept(true) If a noexcept-marked function does throw at runtime, terminate() is called Note that old exception specifications are deprecated since C++11 Destructors are noexcept by default in C++11.

noexcept noexcept as an operator: noexcept(expr) Example: bool b1 = noexcept(2 + 3); // b1 = true bool b2 = noexcept(throw 1); // b2 = false void func1() { } bool b3 = noexcept(func1()); void func2() noexcept { } bool b4 = noexcept(func2()); // b4 = true Used by the standard library to decide between moving or copying Thus, mark your move ctor and move assignment operator noexcept // b3 = false noexcept(2+3), compiler is not going to calculate 2 + 3, but it’s going to figure out if that expression could throw. func1() is clearly not throwing, but it’s not marked as noexcept, thus noexcept(func1()) returns false. Standard library: for example containers: move if no-throw, copy otherwise, that’s why your should define your move constructor and move assignment operator as noexcept.

Inline Namespace Intended for libraries to support versioning Example: // file V98.h: namespace V98 { void f(int); // does something } // file V99.h: inline namespace V99 { void f(int); // does something better than the V98 version void f(double); // new feature // file MyLibrary.h: namespace MyLibrary { #include "V99.h" #include "V98.h" #include "MyLibrary.h" using namespace MyLibrary; V98::f(1); // old version V99::f(1); // new version f(1); // default version

C++11 Core Language Concurrency Features New or updated C++11 core language concurrency features quick_exit() and at_quick_exit() Full support for thread-local storage (partial in VC++2013) Magic statics

quick_exit() and at_quick_exit() quick_exit() terminates application as follows: Calls all functions registered with at_quick_exit() Terminates application Except at_quick_exit() handlers, no other cleanup is done No destructors are called

Thread-Local Storage Keyword: thread_local Each thread gets its own instance Example: thread_local unsigned int data = 1;

Magic Statics Thread-safe “Magic” statics Static local variables are initialized in a thread-safe way No manual synchronization needed for initialization Using statics from multiple threads still requires manual synchronization

Magic Statics Example: simple thread-safe singleton: static Singleton& GetInstance() { static Singleton theInstance; return theInstance; }

C++11 Core Language C99 Features New or updated C++11 core language C99 features __func__

__func__ Standard way to get the name of a function Output: int _tmain(int argc, _TCHAR* argv[]) { cout << __func__ << endl; return 0; } Output: wmain

C++14 Core Language Features New or updated C++14 core language features Binary literals auto and decltype(auto) return types Lambda capture expressions Generic lambdas Digit separators (will be in RTM) Sized deallocation (partial support) Italic features not further discussed.

Binary Literals int value = 0b1111011; // = 123

auto and decltype(auto) Return Types Both auto and decltype(auto) can be used to let the compiler deduce the return type auto strips ref-qualifiers (lvalue and rvalue references) and strips cv-qualifiers (const and volatile) Decltype(auto) does not strip those

auto and decltype(auto) Return Types Example: return type will be int auto Foo(int i) { return i + 1; } Example: return type will be double template<typename T> auto Bar(const T& t) return t * 2; ... auto result = Bar<double>(1.2);

auto and decltype(auto) Return Types Multiple return statements are allowed but all need to be of exactly the same type Following won’t compile returns int and unsigned int auto Foo(int i) { if (i > 1) return 1; else return 2u; }

auto and decltype(auto) Return Types Recursion allowed but there must be a non- recursive return before the recursive call Correct: auto Foo(int i) { if (i == 0) return 0; else return i + Foo(i - 1); } Wrong: auto Foo(int i) { if (i > 0) return i + Foo(i - 1); else return 0; }

decltype(auto) Quick reminder: static const string message = "Test"; const string& Foo() { return message; } ... auto f1 = Foo(); decltype(Foo()) f2 = Foo(); decltype(auto) f3 = Foo();  Type: string  Type: const string&  Type: const string&

auto and decltype(auto) Return Types decltype(auto) as return type Example: auto Foo1(const string& str) { return str; } decltype(auto) Foo2(const string& str) { return str; } decltype(auto) a = Foo1("abc"); decltype(auto) b = Foo2("abc");  Return Type: string  Return Type: const string&

Lambda Capture Expressions Capture expressions to initialize lambda variables Example: float pi = 3.1415; auto myLambda = [myCapture = "Pi: ", pi]{ std::cout << myCapture << pi; }; Lambda has 2 variables: myCapture: a string (not from the enclosing scope) with value “Pi: “ pi: captured from the enclosing scope

Lambda Capture Expressions Allow moving variables into the lambda Example: auto myPtr = std::make_unique<double>(3.1415); auto myLambda = [p = std::move(myPtr)]{ std::cout << *p; }; Lambda has 1 variable: p: a unique_ptr captured and moved from the enclosing scope (could even be called myPtr)

Generic Lambdas Lambda parameters can be declared as auto  auto doubler = [](const auto& value){ return value * 2; }; ... vector<int> v1{ 1, 2, 3 }; transform(begin(v1), end(v1), begin(v1), doubler); vector<double> v2{ 1.1, 2.2, 3.3 }; transform(begin(v2), end(v2), begin(v2), doubler);

Digit Separators (will be in RTM) Single quote character Example: int number1 = 23'456'789; // The number 23456789 float number2 = 0.123'456f; // The number 0.123456

C++14 Library Features New or updated C++14 library features Standard user-defined literals Null forward iterators quoted() Heterogeneous associative lookup Compile-time integer sequences exchange() Dual-range equal(), is_permutation(), mismatch() get<T>() tuple_element_t Italic features not further discussed. quoted() makes working with quoted string values and I/O easier. exchange() assigns a new value to an object and returns its old value.

Standard User-Defined literals “s” for creating std::strings auto myString = "Hello World"s; “h”, “min”, “s”, “ms”, “us”, “ns”, for creating std::chrono::duration time intervals auto myDuration = 42min; “i”, “il”, “if” for creating complex numbers complex<double>, complex<long double>, and complex<float> respectively auto myComplexNumber = 1.3i;

C++17 Core Language Features New or updated C++17 core language features Removing trigraphs Resumable functions (proposal for C++17)

Removing Trigraphs Trigraph = sequence of 3 characters Trigraph Punctuation Character ??= # ??( [ ??/ \ ??) ] ??' ^ ??< { ??! | ??> } ??- ~

Resumable Functions (proposal for C++17) Based on concept of coroutines Coroutine is a generalized routine supporting: Invoke Return Suspend Resume

Resumable Functions (proposal for C++17) Visual C++ 2015 Preview resumable functions restrictions 64-bit targets only Manually add /await compiler switch Manually disable /RTC1 (run-time error checks) Manually disable /sdl (additional security checks) Currently in <experimental\resumable>

Resumable Functions – Async Operations future<int> calculate_the_answer() // This could be some long running computation or I/O { return async([] { this_thread::sleep_for(3s); return 42; }); } future<void> coro() // A resumable function cout << "coro() starting to wait for the answer..." << endl; auto result = __await calculate_the_answer(); cout << "got answer " << result << endl; int main() auto fut = coro(); cout << "main() is writing something" << endl; fut.get(); // Before exiting, let's wait on our asynchronous coro() call to finish. return 0; 2 3 6/5 coro() starting to wait for the answer... main() is writing something got answer 42 1 4 5/6

Resumable Functions – Generator Pattern #include <experimental\resumable> #include <experimental\generator> using namespace std; using namespace std::experimental; generator<int> fib() { int a = 0; int b = 1; for (;;) { __yield_value a; auto next = a + b; a = b; b = next; } 1 2 3 5 8 13 21 34 int main() { for (auto v : fib()) { if (v > 50) { break; } cout << v << endl; }

TS Library Features New or updated Technical Specification library features File system “V3”

Productivity Improvements Enhanced productivity & build-time improvements

Productivity & Build-Time Improvements Improved IntelliSense database buildup Incremental linking with LTCG enabled Incremental linking for static libraries Changes to static libraries referenced by other code modules now link incrementally New fast PDB generation techniques: /Debug:FastLink Substantially decreases link times Object file size reduction Multithreading in the linker New Visual Studio Graphics Analyzer (VSGA) PDB generation: edit/compile/run/… story

Productivity Improvements Simplified QuickInfo for template deduction VC++2013 VC++2015

New Refactorings Rename symbol Implement pure virtuals Create declaration or definition Move function definition Convert to raw string literal Extract function (available from Visual Studio Gallery) Show demo.

New Refactorings Demo

Improved Performance

Improved Performance Improvements to automatic vectorization Vectorization of control flow (if-then-else) Vectorization with /O1 (minimize size) enabled Vectorizing more range-based for loops Improvements to scalar optimizations Better code gen of bit-test operations Control flow merging and optimizations (loop-if switching) Better code gen for std::min and std:max ARM32 code generation improvements

C++ Cross-Platform Mobile Dev

C++ Cross-Platform Mobile Dev VC++ 2015 Preview has 2 compilers: VC++ compiler to target Windows platforms Clang to target Android (iOS coming in the near future) Android support: Build C++ dynamic shared libs and static libs Libs are consumed with Java, Xamarin , … Build Native-Activity apps, pure C++

Android Native-Activity App Demo

Questions ?

Widescreen Test Pattern (16:9) Aspect Ratio Test (Should appear circular) 4x3 16x9