Visual Studio C++ Tutorial
Visual Studio C++ Tutorial
NOTE
This developer documentation applies to Visual Studio 2019. To see the documentation for your preferred version of Visual
Studio, use the Version selector control. It's found at the top of the table of contents on this page.
If you're looking for a Microsoft Visual C++ 2019 redistributable package so that you can run a program, go to the
Microsoft Visual Studio site's Downloads page. Under All Downloads , expand the Other Tools, Frameworks, and
Redistributables section. Select your target architecture, then choose the Download button.
For older redistributables, open the Older downloads page. Expand the Other Tools, Frameworks, and
Redistributables section. Find the redistributable version you want to download, select your target architecture, then
choose the Download button.
NOTE
This developer documentation applies to Visual Studio 2017. To see the documentation for your preferred version of Visual
Studio, use the Version selector control. It's found at the top of the table of contents on this page.
If you're looking for a Microsoft Visual C++ 2017 or older redistributable package so that you can run a program, go to the
Microsoft Visual Studio site's Older downloads page. Expand the Other Tools, Frameworks, and Redistributables
section. Find the redistributable version you want to download, select your target architecture, then choose the Download
button.
NOTE
This developer documentation applies to Visual Studio 2015. To see the documentation for your preferred version of Visual
Studio, use the Version selector control. It's found at the top of the table of contents on this page.
If you're looking for a Microsoft Visual C++ 2015 or older redistributable package so that you can run a program, go to the
Microsoft Visual Studio site's Older downloads page. Expand the Other Tools, Frameworks, and Redistributables
section. Find the redistributable version you want to download, select your target architecture, then choose the Download
button.
Microsoft Visual C++ (MSVC) refers to the C++, C, and assembly language development tools and libraries
available as part of Visual Studio on Windows. These tools and libraries let you create Universal Windows
Platform (UWP) apps, native Windows desktop and server applications, cross-platform libraries and apps that run
on Windows, Linux, Android, and iOS, as well as managed apps and libraries that use the .NET Framework. You
can use MSVC to write anything from simple console apps to the most sophisticated and complex apps for
Windows desktop, from device drivers and operating system components to cross-platform games for mobile
devices, and from the smallest IoT devices to multi-server high performance computing in the Azure cloud.
Visual Studio 2015, 2017 and 2019 can be installed side-by-side. You can use Visual Studio 2019 (compiler toolset
v142) or Visual Studio 2017 (v141) to edit and build programs using the toolset from Visual Studio 2017 (v141)
and Visual Studio 2015 (v140).
Learn C++
Welcome back to C++
Learn more about modern C++ programming techniques based on C++11 and later that enable you to write fast,
safe code and avoid many of the pitfalls of C-style programming.
Standard C++
Learn about C++, get an overview of Modern C++, and find links to books, articles, talks, and events
Learn Visual Studio and make your first C++ project
Start learning how to write C++ in Visual Studio.
Visual Studio C++ samples
Information about the C++ code samples provided by Microsoft.
Languages reference
C++ language reference
The reference guide to the Microsoft implementation of the C++ programming language.
C/C++ preprocessor reference
A common reference to the shared C and C++ language preprocessor.
C language reference
The reference guide to the Microsoft implementation of the C programming language.
Compiler intrinsics and assembly language
Guides to the compiler intrinsics supported or implemented by the Microsoft C/C++ compilers on each platform.
C++ Libraries in Visual Studio
The following sections provide information about the different C and C++ libraries that are included in Visual
Studio.
C runtime library reference
Includes security-enhanced alternatives to functions that are known to pose security issues.
C++ standard library
The C++ Standard Library.
Active Template Library (ATL)
Support for COM components and apps.
Microsoft Foundation Class (MFC) libraries
Support for creating desktop apps that have traditional or Office-style user interfaces.
Parallel Patterns Library (PPL)
Asynchronous and parallel algorithms that execute on the CPU.
C++ AMP (C++ Accelerated Massive Parallelism)
Massively parallel algorithms that execute on the GPU.
Windows Runtime Template Library (WRL)
Universal Windows Platform (UWP) apps and components.
.NET programming with C++/CLI
Programming for the common language runtime (CLR).
As part of the Visual Studio Integrated Development Environment (IDE), Microsoft C++ (MSVC) shares many
windows and tools in common with other languages. Many of those, including Solution Explorer , the code editor,
and the debugger, are documented under Visual Studio IDE. Often, a shared tool or window has a slightly different
set of features for C++ than for other languages. A few windows or tools are only available in Visual Studio
Professional or Visual Studio Enterprise editions.
In addition to shared tools in the Visual Studio IDE, MSVC has several tools specifically for native code
development. These tools are also listed in this article. For a list of which tools are available in each edition of
Visual Studio, see C++ Tools and Features in Visual Studio Editions.
Create projects
A project is basically a set of source code files and resources such as images or data files that are built into an
executable program or library.
Visual Studio provides support for any project system or custom build tools that you wish to use, with full support
for IntelliSense, browsing and debugging:
MSBuild is the native project system for Visual Studio. When you select File > New > Project from the
main menu, you see many kinds of MSBuild project templates that get you started quickly developing
different kinds of C++ applications.
In general, you should use these templates for new projects unless you are using existing CMake projects, or
you are using another project system. For more information, see Creating and managing MSBuild-based
projects.
CMake is a cross-platform build system that is integrated into the Visual Studio IDE when you install the
Desktop development with C++ workload. You can use the CMake project template for new projects, or
simply open a folder with a CMakeLists.txt file. For more information, see CMake projects in Visual Studio.
Any other C++ build system, including a loose collection of files, is supported via the Open Folder feature.
You create simple JSON files to invoke your build program and configure debugging sessions. For more
information, see Open Folder projects for C++.
Obtain libraries
Use the vcpkg package manager to obtain and install third-party libraries. Over 900 open-source libraries are
currently available in the catalog.
Write code
After you create a project, all the project files are displayed in the Solution Explorer window. (A solution is a
logical container for one or more related projects.) When you click on a .h or .cpp file in Solution Explorer , the file
opens up in the code editor.
The code editor is a specialized word processor for C++ source code. It color-codes language keywords, method
and variable names, and other elements of your code to make the code more readable and easier to understand. It
also provides tools for refactoring code, navigating between different files, and understanding how the code is
structured. For more information, see Writing and refactoring code.
For more information about configuring builds, see Working with Project Properties and Projects and build
systems.
You can also use the compiler (cl.exe) and many other build-related standalone tools such as NMAKE and LIB
directly from the command line. For more information, see Build C/C++ code on the command line and C/C++
Building Reference.
Debug
You can start debugging by pressing F5 . Execution pauses on any breakpoints you have set (by pressing F9 ). You
can also step through code one line at a time (F10 ), view the values of variables or registers, and even in some
cases make changes in code and continue debugging without re-compiling. The following illustration shows a
debugging session in which execution is stopped on a breakpoint. The values of the data structure members are
visible in the Watch Window .
For more information, see Debugging in Visual Studio.
Test
Visual Studio includes the Microsoft Unit Test Framework for C++, as well as support for Boost.Test, Google Test,
and CTest. Run your tests from the Test Explorer window:
For more information, see Verifying Code by Using Unit Tests and Write unit tests for C/C++ in Visual Studio.
Analyze
Visual Studio includes static code analysis tools that can detect potential problems in your source code. These tools
include an implementation of the C++ Core Guidelines rules checkers. For more information, see Code analysis for
C/C++ overview.
Next steps
Explore Visual Studio further by following along with one of these introductory articles:
Learn to use the code editor
Learn about projects and solutions
What's new for C++ in Visual Studio
12/18/2020 • 41 minutes to read • Edit Online
Visual Studio 2019 brings many updates and fixes to the Microsoft C++ environment. We've fixed many bugs and
issues in the compiler and tools. Many of these issues were submitted by customers through the Report a Problem
and Provide a Suggestion options under Send Feedback . Thank you for reporting bugs! For more information on
what's new in all of Visual Studio, visit What's new in Visual Studio 2019. For information on what's new for C++ in
Visual Studio 2017, see . For information on what's new for C++ in Visual Studio 2015 and earlier versions, see
What's new f or C++ in Visual Studio 2017
C++ compiler
Enhanced support for C++17 features and correctness fixes, plus experimental support for C++20 features
such as modules and coroutines. For detailed information, see C++ Conformance Improvements in Visual
Studio 2019.
The /std:c++latest option now includes C++20 features that aren't necessarily complete, including initial
support for the C++20 operator <=> ("spaceship") for three-way comparison.
The C++ compiler switch /Gm is now deprecated. Consider disabling the /Gm switch in your build scripts if
it's explicitly defined. However, you can also safely ignore the deprecation warning for /Gm , because it's not
treated as an error when using "Treat warnings as errors" ( /WX ).
As MSVC begins implementing features from the C++20 standard draft under the /std:c++latest flag,
/std:c++latest is now incompatible with /clr (all flavors), /ZW , and /Gm . In Visual Studio 2019, use
/std:c++17 or /std:c++14 modes when compiling with /clr , /ZW , or /Gm (but see previous bullet).
Precompiled headers are no longer generated by default for C++ console and desktop apps.
Codegen, security, diagnostics, and versioning
Improved analysis with /Qspectre for providing mitigation assistance for Spectre Variant 1 (CVE-2017-5753). For
more information, see Spectre Mitigations in MSVC.
C++ IDE
Live Share C++ support
Live Share now supports C++, allowing developers using Visual Studio or Visual Studio Code to collaborate in real
time. For more information, see Announcing Live Share for C++: Real-Time Sharing and Collaboration
IntelliCode for C++
Vi su a l St u d i o 2 0 1 9 v e r si o n 1 6 .1
IntelliCode uses its own extensive training and your code context to put what you're most likely to use at the top of
your completion list. It can often eliminate the need to scroll down through the list. For C++, IntelliCode offers the
most help when using popular libraries such as the standard library. IntelliCode is an optional extension available
as a workload component in the installer. For more information, see AI-Assisted Code Completion Suggestions
Come to C++ via IntelliCode.
Template IntelliSense
The Template Bar now uses the Peek Window UI rather than a modal window, supports nested templates, and
pre-populates any default arguments into the Peek Window . For more information, see Template IntelliSense
Improvements for Visual Studio 2019 Preview 2. A Most Recently Used dropdown in the Template Bar enables
you to quickly switch between previous sets of sample arguments.
New Start window experience
When launching the IDE, a new Start window appears. It has options to open recent projects, clone code from
source control, open local code as a solution or a folder, or create a new project. The New Project dialog has also
been overhauled into a search-first, filterable experience.
New names for some project templates
We've modified several project template names and descriptions to fit with the updated New Project dialog.
Various productivity improvements
Visual Studio 2019 includes the following features that will help make coding easier and more intuitive:
Quick fixes for:
Add missing #include
NULL to nullptr
Add missing semicolon
Resolve missing namespace or scope
Replace bad indirection operands (* to & and & to *)
Quick Info for a block by hovering on closing brace
Peek Header / Code File
Go to Definition on #include opens the file
For more information, see C++ Productivity Improvements in Visual Studio 2019 Preview 2.
QuickInfo improvements
Vi su a l St u d i o 2 0 1 9 v e r si o n 1 6 .1
The Quick Info tooltip now respects the semantic colorization of your editor. It also has a new Search Online link
that will search for online docs to learn more about the hovered code construct. The link provided by Quick Info for
red-squiggled code will search for the error online. That way you don't need to retype the message into your
browser. For more information, see Quick Info Improvements in Visual Studio 2019: Colorization and Search
Online.
IntelliCode available in C++ workload
Vi su a l St u d i o 2 0 1 9 v e r si o n 1 6 .1
IntelliCode now ships as an optional component in the Desktop Development with C++ workload. For more
information, see Improved C++ IntelliCode now Ships with Visual Studio 2019.
CMake support
Support for CMake 3.14
Visual Studio can now open existing CMake caches generated by external tools, such as CMakeGUI,
customized meta-build systems or build scripts that invoke cmake.exe themselves.
Improved IntelliSense performance.
A new settings editor provides an alternative to manually editing the CMakeSettings.json file, and provides
some parity with CMakeGUI.
Visual Studio helps bootstrap your C++ development with CMake on Linux by detecting if you have a
compatible version of CMake on your Linux machine. If not, it offers to install it for you.
Incompatible settings in CMakeSettings, such as mismatched architectures or incompatible CMake
generator settings, show squiggles in the JSON editor and errors in the error list.
The vcpkg toolchain is automatically detected and enabled for CMake projects that are opened in the IDE
once vcpkg integrate install has been run. This behavior can be turned off by specifying an empty
toolchain file in CMakeSettings.
CMake projects now enable Just My Code debugging by default.
Static analysis warnings are now processed in the background and displayed in the editor for CMake
projects.
Clearer build and configure 'begin' and 'end' messages for CMake projects and support for Visual Studio's
build progress UI. Additionally, there's now a CMake verbosity setting in Tools > Options to customize the
detail level of CMake build and configuration messages in the Output Window.
The cmakeToolchain setting is now supported in CMakeSettings.json to specify toolchains without manually
modifying the CMake command line.
A new Build All menu shortcut Ctrl+Shift+B .
Vi su a l St u d i o 2 0 1 9 v e r si o n 1 6 .1
Integrated support for editing, building, and debugging CMake projects with Clang/LLVM. For more
information, see Clang/LLVM Support in Visual Studio.
Linux and the Windows Subsystem for Linux
Vi su a l St u d i o 2 0 1 9 v e r si o n 1 6 .1
Support for AddressSanitizer (ASan) in Linux and CMake cross-platform projects. For more information, see
AddressSanitizer (ASan) for the Linux Workload in Visual Studio 2019.
Integrated Visual Studio support for using C++ with the Windows Subsystem for Linux (WSL). For more
information, see C++ with Visual Studio 2019 and Windows Subsystem for Linux (WSL).
IncrediBuild integration
IncrediBuild is included as an optional component in the Desktop development with C++ workload. The
IncrediBuild Build Monitor is fully integrated in the Visual Studio IDE. For more information, see Visualize your
build with IncrediBuild's Build Monitor and Visual Studio 2019.
Debugging
For C++ applications running on Windows, PDB files now load in a separate 64-bit process. This change
addresses a range of crashes caused by the debugger running out of memory. For example, when
debugging applications that contain a large number of modules and PDB files.
Search is enabled in the Watch , Autos , and Locals windows.
Code analysis
Code analysis now runs automatically in the background. Warnings display as green squiggles in-editor as
you type. For more information, see In-editor code analysis in Visual Studio 2019 Preview 2.
New experimental ConcurrencyCheck rules for well-known standard library types from the <mutex>
header. For more information, see Concurrency Code Analysis in Visual Studio 2019.
An updated partial implementation of the Lifetime profile checker, which detects dangling pointers and
references. For more information, see Lifetime Profile Update in Visual Studio 2019 Preview 2.
More coroutine-related checks, including C26138, C26810, C26811, and the experimental rule C26800. For
more information, see New Code Analysis Checks in Visual Studio 2019: use-after-move and coroutine.
Vi su a l St u d i o 2 0 1 9 v e r si o n 1 6 .1
New quick fixes for uninitialized variable checks. For more information, see New code analysis quick fixes for
uninitialized memory (C6001) and use before init (C26494) warnings.
Unit testing
The Managed C++ Test Project template is no longer available. You can continue using the Managed C++ Test
framework in your existing projects. For new unit tests, consider using one of the native test frameworks for which
Visual Studio provides templates (MSTest, Google Test), or the Managed C# Test Project template.
Visual Studio 2017 brings many updates and fixes to the C++ environment. We've fixed over 250 bugs and
reported issues in the compiler and tools. Many were submitted by customers through the Report a Problem and
Provide a Suggestion options under Send Feedback . Thank you for reporting bugs! For more information on
what's new in all of Visual Studio, see What's new in Visual Studio 2017. For information on what's new for C++ in
Visual Studio 2019, see . For information on what's new for C++ in Visual Studio 2015 and earlier versions, see
What's new f or C++ in Visual Studio
The compiler supports about 75% of the features that are new in C++17, including structured bindings, constexpr
lambdas, if constexpr , inline variables, fold expressions, and adding noexcept to the type system. These features
are available under the /std:c++17 option. For more information, see C++ Conformance Improvements in Visual
Studio 2017
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .7
The MSVC compiler toolset in Visual Studio version 15.7 now conforms with the C++ Standard. For more
information, see Announcing: MSVC Conforms to the C++ Standard and Microsoft C++ Language Conformance.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .8
The /experimental:preprocessor compiler switch enables the new experimental MSVC preprocessor that will
eventually conform to all applicable C and C++ standards. For more information, see MSVC new preprocessor
overview.
New compiler options
/permissive- : Enable all strict standards conformance compiler options and disable most Microsoft-specific
compiler extensions (but not __declspec(dllimport) , for example). This option is on by default in Visual
Studio 2017 version 15.5. The /permissive- conformance mode includes support for two-phase name
lookup. For more information, see C++ Conformance Improvements in Visual Studio.
/diagnostics : Enables display of the diagnostic error or warning location three different ways: just the line
number, the line number and column, or the line number and column, with a caret under the offending line
of code.
/debug:fastlink : Enable up to 30% faster incremental link times (vs. Visual Studio 2015) by not copying all
debug information into the PDB file. The PDB file instead points to the debug information for the object and
library files used to create the executable. See Faster C++ build cycle in VS "15" with /Debug:fastlink and
Recommendations to speed C++ builds in Visual Studio.
Visual Studio 2017 allows using /sdl with /await . We removed the /RTC limitation with Coroutines.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .3
/std:c++14 and /std:c++latest : These compiler options enable you to opt in to specific versions of the ISO
C++ programming language in a project. Most of the new draft standard features are guarded by the
/std:c++latest option.
/std:c++17enables the set of C++17 features implemented by the compiler. This option disables compiler
and standard library support for features after C++17: ones that are changed or new in later versions of the
Working Draft, and defect updates of the C++ Standard. To enable those features, use /std:c++latest .
Codegen, security, diagnostics, and versioning
This release brings several improvements in optimization, code generation, toolset versioning, and diagnostics.
Some notable improvements include:
Improved code generation of loops: Support for automatic vectorization of division of constant integers, better
identification of memset patterns.
Improved code security: Improved emission of buffer overrun compiler diagnostics, and /guard:cf now guards
switch statements that generate jump tables.
Versioning: The value of the built-in preprocessor macro _MSC_VER is now being monotonically updated at
every Visual C++ toolset update. For more information, see Visual C++ Compiler Version.
New toolset layout: The compiler and related build tools have a new location and directory structure on your
development machine. The new layout enables side-by-side installations of multiple versions of the compiler.
For more information, see Compiler Tools Layout in Visual Studio 2017.
Improved diagnostics: The output window now shows the column where an error occurs. For more information,
see C++ compiler diagnostics improvements in VS "15" Preview 5.
When using coroutines, the experimental keyword yield (available under the /await option) has been
removed. Your code should be updated to use co_yield instead. For more information, see yield keyword to
become co_yield in VS 2017.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .3
Additional improvements to diagnostics in the compiler. For more information, see Diagnostic Improvements in
Visual Studio 2017 15.3.0.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .5
Visual C++ runtime performance continues to improve through better generated code quality. Now you can just
recompile your code, and your app runs faster. Some of the compiler optimizations are brand new, such as the
vectorization of conditional scalar stores, the combining of calls sin(x) and cos(x) into a new sincos(x) , and
the elimination of redundant instructions from the SSA optimizer. Other compiler optimizations are improvements
to existing functionality, such as: vectorizer heuristics for conditional expressions, better loop optimizations, and
float min/max codegen. The linker has a new and faster /OPT:ICF implementation, which can result in up to 9%
link-time speedups, and there are other perf fixes in incremental linking. For more information, see /OPT
(Optimizations) and /INCREMENTAL (Link Incrementally).
The Microsoft C++ compiler supports Intel's AVX-512. It has Vector Length instructions that bring new functions in
AVX-512 to 128-bit and 256-bit wide registers.
The /Zc:noexceptTypes- option can be used to revert to the C++14 version of noexcept while using C++17 mode
in general. This option enables you to update your source code to conform to C++17 without having to rewrite all
your throw() code at the same time. For more information, see Dynamic exception specification removal and
noexcept.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .7
New compiler switch /Qspectre to help mitigate against speculative execution side-channel attacks. For more
information, see Spectre mitigations in MSVC.
New diagnostic warning for Spectre mitigation. For more information, see Spectre diagnostic in Visual Studio
2017 Version 15.7 Preview 4.
A new value for /Zc, /Zc:__cplusplus , enables correct reporting of the C++ standard support. For example,
when the switch is set and the compiler is in /std:c++17 mode the value expands to 201703L . For more
information, see MSVC now correctly reports __cplusplus.
Minor basic_string _ITERATOR_DEBUG_LEVEL != 0 diagnostics improvements. When an IDL check gets tripped in
string machinery, it will now report the specific behavior that caused the trip. For example, instead of "string
iterator not dereferencable" you'll get "cannot dereference string iterator because it is out of range (e.g. an end
iterator)".
Fixed the std::promise move assignment operator, which previously could cause code to block forever.
Fixed compiler errors with the atomic<T*> implicit conversion to T* .
pointer_traits<Ptr> now correctly detects Ptr::rebind<U> .
Fixed a missing const qualifier in the move_iterator subtraction operator.
Fixed silent bad codegen for stateful user-defined allocators requesting
propagate_on_container_copy_assignment and propagate_on_container_move_assignment .
atomic<T> now tolerates overloaded operator&() .
Slightly improved compiler diagnostics for incorrect bind() calls.
There are more standard library improvements in Visual Studio 2017 RTM. For a complete list, see the C++ Team
Blog entry Standard Library Fixes In VS 2017 RTM.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .3
std::partition now calls the predicate N times instead of N + 1 times, as the standard requires.
Attempts to avoid magic statics in version 15.3 have been repaired in version 15.5.
std::atomic<T> no longer requires T to be default constructible.
Heap algorithms that take logarithmic time behave differently when iterator debugging is enabled. They no
longer do a linear time assertion that the input is in fact a heap.
__declspec(allocator) is now guarded for C1XX only, to prevent warnings from Clang, which doesn't
understand this declspec.
basic_string::npos is now available as a compile time constant.
std::allocator in C++17 mode now properly handles allocation of over-aligned types, that is, types whose
alignment is greater than max_align_t , unless disabled by /Zc:alignedNew- . For example, vectors of objects
with 16-byte or 32-byte alignment are now properly aligned for SSE and AVX instructions.
Conformance improvements
We added <any>, <string_view>, apply() , make_from_tuple() .
Added <optional>, <variant>, shared_ptr::weak_type , and <cstdalign>.
Enabled C++14 constexpr in min(initializer_list) , max(initializer_list) , and minmax(initializer_list) ,
and min_element() , max_element() , and minmax_element() .
Several additional C++17 features have been implemented. For more information, see Microsoft C++ language
conformance table.
Implemented P0602R0 "variant and optional should propagate copy/move triviality".
The standard library now officially tolerates dynamic RTTI being disabled via the /GR- option. Both
dynamic_pointer_cast() and rethrow_if_nested() inherently require dynamic_cast , so the standard library
now marks them as =delete under /GR- .
Even when dynamic RTTI has been disabled via /GR- , "static RTTI" in the form of typeid(SomeType) is still
available, and powers several standard library components. The standard library now supports disabling this
feature too, via /D_HAS_STATIC_RTTI=0 . This flag also disables std::any , the target() and target_type()
member functions of std::function , and the get_deleter() friend member function of std::shared_ptr and
std::weak_ptr .
The standard library now uses C++14 constexpr unconditionally, instead of conditionally defined macros.
The standard library now uses alias templates internally.
The standard library now uses nullptr internally, instead of nullptr_t{} . (Internal usage of NULL has been
eradicated. Internal usage of 0-as-null is being cleaned up gradually.)
The standard library now uses std::move() internally, instead of stylistically misusing std::forward() .
Changed static_assert(false, "message") to #error message . This change improves compiler diagnostics
because #error immediately stops compilation.
The standard library no longer marks functions as __declspec(dllimport) . Modern linker technology no longer
requires it.
Extracted SFINAE to default template arguments, which reduced clutter compared to return types and function
argument types.
Debug checks in <random> now use the standard library's usual machinery, instead of the internal function
_Rng_abort() , which called fputs() to stderr . This function's implementation has been kept for binary
compatibility. We'll remove it in the next binary-incompatible version of the standard library.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .5
Several standard library features have been added, deprecated, or removed per the C++17 standard. For more
information, see C++ conformance improvements in Visual Studio.
Experimental support for the following parallel algorithms:
all_of
any_of
for_each
for_each_n
none_of
reduce
replace
replace_if
sort
The signatures for the following parallel algorithms are added but not parallelized at this time. Profiling showed
no benefit in parallelizing algorithms that only move or permute elements:
copy
copy_n
fill
fill_n
move
reverse
reverse_copy
rotate
rotate_copy
swap_ranges
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .6
<memory_resource>
Library Fundamentals V1
Deleting polymorphic_allocator assignment
Improving class template argument deduction
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .7
Worked around interactions with noexcept , which prevented inlining the std::atomic implementation into
functions that use Structured Exception Handling (SEH).
Changed the standard library's internal _Deallocate() function to optimize into smaller code, allowing it to be
inlined into more places.
Changed std::try_lock() to use pack expansion instead of recursion.
Improved the std::lock() deadlock avoidance algorithm to use lock() operations instead of spinning on
try_lock() on all the locks.
Enabled the Named Return Value Optimization in system_category::message() .
conjunction and disjunction now instantiate N + 1 types, instead of 2N + 2 types.
std::function no longer instantiates allocator support machinery for each type-erased callable, improving
throughput and reducing .obj size in programs that pass many distinct lambdas to std::function .
allocator_traits<std::allocator> contains manually inlined std::allocator operations, reducing code size in
code that interacts with std::allocator through allocator_traits only (that is, in most code).
The C++11 minimal allocator interface is now handled by the standard library calling allocator_traits
directly, instead of wrapping the allocator in an internal class _Wrap_alloc . This change reduces the code size
generated for allocator support, improves the optimizer's ability to reason about standard library containers in
some cases, and provides a better debugging experience (as now you see your allocator type, rather than
_Wrap_alloc<your_allocator_type> in the debugger).
Removed metaprogramming for customized allocator::reference , which allocators aren't allowed to
customize. (Allocators can make containers use fancy pointers but not fancy references.)
The compiler front end was taught to unwrap debug iterators in range-based for loops, improving the
performance of debug builds.
The basic_string internal shrink path for shrink_to_fit() and reserve() is no longer in the path of
reallocating operations, reducing code size for all mutating members.
The basic_string internal grow path is no longer in the path of shrink_to_fit() .
The basic_string mutating operations are now factored into non-allocating fast path and allocating slow path
functions, making it more likely for the common no-reallocate case to be inlined into callers.
The basic_string mutating operations now construct reallocated buffers in the preferred state rather than
resizing in place. For example, an insert at the beginning of a string now moves the content after the insertion
exactly once. It's moved either down or to the newly allocated buffer. It's no longer moved twice in the
reallocating case, first to the newly allocated buffer and then down.
Operations calling the C standard library in <string> now cache the errno address to remove repeated
interaction with TLS.
Simplified the is_pointer implementation.
Finished changing function-based Expression SFINAE to struct and void_t -based.
Standard library algorithms now avoid postincrementing iterators.
Fixed truncation warnings when using 32-bit allocators on 64-bit systems.
std::vector move assignment is now more efficient in the non-POCMA non-equal-allocator case, by reusing
the buffer when possible.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .5
basic_string<char16_t> now engages the same memcmp , memcpy , and similar optimizations that
basic_string<wchar_t> engages.
An optimizer limitation that prevented function pointers from being inlined, exposed by our "avoid copying
functions" work in Visual Studio 2015 Update 3, has been worked around, restoring performance of
lower_bound(iter, iter, function pointer) .
The overhead of iterator debugging's order verification of inputs to includes , set_difference ,
set_symmetric_difference , and set_union was reduced by unwrapping iterators before checking order.
std::inplace_merge now skips over elements that are already in position.
Constructing std::random_device no longer constructs and then destroys a std::string .
std::equal and std::partition had a jump-threading optimization pass that saves an iterator comparison.
When std::reverse is passed pointers to trivially copyable T , it will now dispatch to a handwritten vectorized
implementation.
std::fill , std::equal , and std::lexicographical_compare were taught how to dispatch to memset and
memcmp for std::byte and gsl::byte (and other char-like enums and enum classes). Since std::copy
dispatches using is_trivially_copyable , it didn't need any changes.
The standard library no longer contains empty-braces destructors whose only behavior was to make types
non-trivially-destructible.
Other Libraries
Open-source library support
Vcpkg is an open-source command-line tool that greatly simplifies the process of acquiring and building open-
source C++ static libs and DLLS in Visual Studio. For more information, see vcpkg: A package manager for C++.
CPPRest SDK 2.9.0
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .5
The CPPRestSDK, a cross-platform web API for C++, has been updated to version 2.9.0. For more information, see
CppRestSDK 2.9.0 is available on GitHub.
ATL
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .5
Several project and code wizards have been rewritten in the signature dialog style.
Add Class now launches the Add Class wizard directly. All of the other items that were previously here are now
available under Add > New Item .
Win32 projects are now under the Windows Desktop category in the New Project dialog.
The Windows Console and Desktop Application templates now create the projects without displaying a
wizard. There's a new Windows Desktop Wizard under the same category that displays the same options as
the old Win32 Console Application wizard.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .5
Several C++ operations that use the IntelliSense engine for refactoring and code navigation run much faster. The
following numbers are based on the Visual Studio Chromium solution with 3500 projects:
Rename 5.3x
C++ now supports Ctrl+Click Go To Definition , making mouse navigation to definitions easy. The Structure
Visualizer from the Productivity Power Tools pack is now also included in the product by default.
IntelliSense
The new SQLite-based database engine is now being used by default. The new engine speeds up database
operations like Go To Definition and Find All References . It significantly improves initial solution parse
time. The setting has moved to Tools > Options > Text Editor > C/C++ > Advanced . (It was formerly
under ...C/C++ > Experimental.)
We've improved IntelliSense performance on projects and files not using precompiled headers - an
Automatic Precompiled Header will be created for headers in the current file.
We've added error filtering and help for IntelliSense errors in the error list. Clicking on the error column
now allows for filtering. Also, clicking on the specific errors or pressing F1 will launch an online search for
the error message.
Added a new experimental Predictive IntelliSense feature that provides contextually aware filtering of what
appears in the Member List. For more information, see C++ IntelliSense Improvements - Predictive
IntelliSense & Filtering.
Find All References (Shift+F12) now helps you get around easily, even in complex codebases. It provides
advanced grouping, filtering, sorting, searching within results, and (for some languages) colorization, so you
can get a clear understanding of your references. For C++, the new UI includes information about whether
we're reading from or writing to a variable.
The Dot-to-Arrow IntelliSense feature has been moved from experimental to advanced, and is now enabled
by default. The editor features Expand Scopes and Expand Precedence have also been moved from
experimental to advanced.
The experimental refactoring features Change Signature and Extract Function are now available by
default.
Added an experimental 'Faster project load' feature for C++ projects. The next time you open a C++ project
it will load faster, and the time after that it will load much faster!
Some of these features are common to other languages, and some are specific to C++. For more
information about these new features, see Announcing Visual Studio "15" Preview 5.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .7
Support added for ClangFormat. For more information, see ClangFormat Support in Visual Studio 2017.
Improved support for alternative compilers and build environments such as MinGW and Cygwin. For more
information, see Using MinGW and Cygwin with Visual C++ and Open Folder.
Added support to define global and configuration-specific environment variables in CppProperties.json and
CMakeSettings.json. These environment variables can be consumed by debug configurations defined in
launch.vs.json and tasks in tasks.vs.json. For more information, see Customizing your Environment with Visual
C++ and Open Folder.
Improved support for CMake's Ninja generator, including the ability to easily target 64-bit platforms.
Support added for CMake 3.11, code analysis in CMake projects, Targets view in Solution Explorer, options for
cache generation, and single file compilation. For more information, see CMake Support in Visual Studio and
CMake projects in Visual Studio.
The Visual C++ Build tools (previously available as a standalone product) are now included as a workload in the
Visual Studio Installer. This workload installs only the tools required to build C++ projects without installing the
Visual Studio IDE. Both the v140 and v141 toolsets are included. The v141 toolset contains the latest
improvements in Visual Studio 2017 version 15.5. For more information, see Visual Studio Build Tools now include
the VS2017 and VS2015 MSVC Toolsets.
Improvements have been made in cross-platform code sharing and type visualization. For more information, see
Linux C++ improvements for cross-platform code sharing and type visualization.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .5
The Linux workload has added support for rsync as an alternative to sftp for synchronizing files to remote
Linux machines.
Support is added for cross compilation targeting ARM microcontrollers. To enable it in the installation, choose
the Linux development with C++ workload and select the option for Embedded and IoT Development .
This option adds the ARM GCC cross compilation tools and Make to your installation. For more information, see
ARM GCC Cross Compilation in Visual Studio.
Support added for CMake. You can now work on your existing CMake code base without having to convert it to
a Visual Studio project. For more information, see Configure a Linux CMake Project.
Support added for running remote tasks. This capability allows you to run any command on a remote system
that is defined in Visual Studio's Connection Manager. Remote tasks also provide the capability to copy files to
the remote system. For more information, see Configure a Linux CMake Project.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .7
Various improvements to Linux workload scenarios. For more information, see Linux C++ Workload
improvements to the Project System, Linux Console Window, rsync and Attach to Process.
IntelliSense for headers on remote Linux connections. For more information, see IntelliSense for Remote Linux
Headers and Configure a Linux CMake Project.
A Windows Application Packaging Project project template is added, which greatly simplifies packaging of
desktop applications with Desktop Bridge. It's available under File | New | Project | Installed | Visual C++ |
Universal Windows Platform . For more information, see Package an app by using Visual Studio (Desktop
Bridge).
When writing new code, you can now use C++/WinRT, a standard C++ language projection for the Windows
Runtime implemented solely in header files. It allows you to consume and author Windows Runtime APIs using
any standards-compliant C++ compiler. C++/WinRT is designed to provide C++ developers with first-class access
to the modern Windows API. For more information, see C++/WinRT.
Starting in build 17025 of the Windows SDK Insider Preview, C++/WinRT is included in the Windows SDK. For
more information, see C++/WinRT is now included the Windows SDK.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .3
New C++ Core Guidelines checks cover smart pointer correctness, correct use of global initializers, and
flagging uses of constructs like goto and bad casts.
Some warning numbers you may find in 15.3 are no longer available in 15.5. These warnings were replaced
with more specific checks.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .6
Support added for single-file analysis, and improvements in analysis run-time performance. For more
information, see C++ Static Analysis Improvements for Visual Studio 2017 15.6 Preview 2
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .7
Support added for /analyze:ruleset , which lets you specify the code analysis rules to run.
Support added for additional C++ Core Guidelines rules. For more information, see Using the C++ Core
Guidelines checkers.
Unit testing in Visual Studio 2017
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .5
Google Test Adapter and Boost.Test Adapter are now available as components of the Desktop Development
with C++ workload. They're integrated with Test Explorer . CTest support is added for CMake projects (using
Open Folder), although full integration with Test Explorer isn't available yet. For more information, see Writing
unit tests for C/C++.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .6
For more information, see Boost.Test Unit Testing: Dynamic Library support and New Item Template.
Vi su a l St u d i o 2 0 1 7 v e r si o n 1 5 .7
CodeLens support added for C++ unit test projects. For more information, see Announcing CodeLens for C++
Unit Testing.
Search and filter in the object table: Provides a quick and easy way to find the resources you're looking
for.
Resource Histor y: This new view provides a streamlined way of seeing the entire modification history of a
resource as it was used during the rendering of a captured frame. To invoke the history for any resource,
click the clock icon next to any resource hyperlink.
It displays the new Resource Histor y tool window, populated with the change history of the resource.
You can capture frames with full call stack capturing enabled. That lets you quickly deduce the context of
each change event, and inspect it within your Visual Studio project. Set the full stack capture option in the
Visual Studio Tools > Options dialog under Graphics Diagnostics .
API Statistics: View a high-level summary of API usage in your frame. It's handy for discovering calls you
may not realize you're making at all, or calls you're making too often. This window is available via View >
API Statistics in Visual Studio Graphics Analyzer.
Memor y Statistics: View how much memory the driver allocates for the resources you create in the
frame. This window is available via View > Memor y Statistics in Visual Studio Graphics Analyzer . To
copy data to a CSV file for viewing in a spreadsheet, right-click and choose Copy All .
Frame Validation: The new errors and warnings list provides an easy way to navigate your event list
based on potential issues detected by the Direct3D debug layer. Click View > Frame Validation in Visual
Studio Graphics Analyzer to open the window. Then click Run Validation to start the analysis. It can take
several minutes to complete, depending on the frame's complexity.
Frame Analysis for D3D12: Use Frame Analysis to analyze draw-call performance with directed "what-if"
experiments. Switch to the Frame Analysis tab and run analysis to view the report. For more details, watch
the GoingNative 25: Visual Studio Graphics Frame Analysis video.
GPU Usage Improvements: Open traces can be taken via the Visual Studio GPU Usage profiler with
either GPU View or the Windows Performance Analyzer (WPA) tool for more detailed analysis. If you have
the Windows Performance Toolkit installed, there are two hyperlinks: one for WPA and another for GPU
View, at the bottom right of the session overview.
Traces you open in GPU View via this link support synchronized VS and GPU View timeline zooming and
panning. A checkbox in VS controls whether synchronization is enabled or not.
For the complete list of what's new through Visual Studio 2015 Update 3, see Visual C++ What's New 2003
through 2015.
For more information on what's new in all of Visual Studio 2015, see the release notes. They're linked from Visual
Studio 2015 Release Notes History.
For information on what's new for C++ in Visual Studio 2019, see .
What's new f or C++ in Visual Studio 2019
For information on what's new for C++ in Visual Studio 2017, see .
What's new f or C++ in Visual Studio 2017
C++ conformance improvements in Visual Studio
12/18/2020 • 106 minutes to read • Edit Online
Microsoft C++ makes conformance improvements and bug fixes in every release. This article lists the
improvements by major release, then by version. It also lists major bug fixes by version. To jump directly to the
changes for a specific version, use the In this ar ticle list.
struct A
{
A() = delete; // user-declared ctor
};
struct B
{
B() = default; // user-declared ctor
int i = 0;
};
P0515R3 C++20 introduces the <=> three-way comparison operator, also known as the "spaceship operator".
Visual Studio 2019 in /std:c++latest mode introduces partial support for the operator by raising errors for
syntax that is now disallowed. For example, the following code compiles without errors in Visual Studio 2017 but
raises multiple errors in Visual Studio 2019 under /std:c++latest :
struct S
{
bool operator<=(const S&) const { return true; }
};
To avoid the errors, insert a space in the offending line before the final angle bracket: U<&S::operator<= > u; .
References to types with mismatched cv-qualifiers
Previously, MSVC allowed direct binding of a reference from a type with mismatched cv-qualifiers below the top
level. This binding could allow modification of supposedly const data referred to by the reference. The compiler
now creates a temporary, as required by the standard. In Visual Studio 2017, the following code compiles without
warnings. In Visual Studio 2019, the compiler raises warning C4172:
<func:#1 "?PData@X@@QBEABQBXXZ"> returning address of local variable or temporary. :
struct X
{
const void* const& PData() const
{
return _pv;
}
void* _pv;
};
int main()
{
X x;
auto p = x.PData(); // C4172
}
int main()
{
fp r = reinterpret_cast<fp>(&f);
}
int main()
{
fp r = static_cast<fp>(&f); // or just &f;
}
Lambda closures
In C++14, lambda closure types aren't literals. The primary consequence of this rule is that a lambda may not be
assigned to a constexpr variable. The following code compiles without errors in Visual Studio 2017, but in Visual
Studio 2019 it raises error C2127:
'l': illegal initialization of 'constexpr' entity with a non-constant expression :
int main()
{
constexpr auto l = [] {}; // C2127 in VS2019
}
To avoid the error, either remove the constexpr qualifier, or else change the conformance mode to /std:c++17 .
std::create_directory failure codes
Implemented P1164 from C++20 unconditionally. This changes std::create_directory to check whether the
target was already a directory on failure. Previously, all ERROR_ALREADY_EXISTS type errors were turned into
success-but-directory-not-created codes.
operator<<(std::ostream, nullptr_t)
Per LWG 2221, added operator<<(std::ostream, nullptr_t) for writing nullptrs to streams.
Additional parallel algorithms
New parallel versions of is_sorted , is_sorted_until , is_partitioned , set_difference , set_intersection ,
is_heap , and is_heap_until .
atomic initialization
P0883 "Fixing atomic initialization" changes std::atomic to value-initialize the contained T rather than default-
initializing it. The fix is enabled when using Clang/LLVM with the Microsoft standard library. It's currently disabled
for the Microsoft C++ compiler, as a workaround for a bug in constexpr processing.
remove_cvref and remove_cvref_t
Implemented the remove_cvref and remove_cvref_t type traits from P0550. These remove reference-ness and
cv-qualification from a type without decaying functions and arrays to pointers (unlike std::decay and
std::decay_t ).
#include <type_traits>
using T = std::identity<int>::type;
T x, y = std::identity<T>{}(x);
int i = 42;
long j = std::identity<long>{}(i);
The following example shows how to use the new std::identity (defined in <functional>) together with the
new std::type_identity :
#include <type_traits>
#include <functional>
using T = std::type_identity<int>::type;
T x, y = std::identity{}(x);
int i = 42;
long j = static_cast<long>(i);
In Visual Studio 2017, this code compiles without warnings, but in Visual Studio 2019 it produces error C2760
syntax error: unexpected token '\<id-expr>', expected 'id-expression' :
void f() {
auto a = [](auto arg) {
decltype(arg)::Type t;
};
}
The following example shows the correct syntax, now enforced by the compiler:
void f() {
auto a = [](auto arg) {
typename decltype(arg)::Type t;
};
}
int main() {
static_assert(noexcept(f()), "f should be noexcept"); // C2338 in 16.2
}
To fix the error, add the noexcept expression to the function declaration:
int main() {
static_assert(noexcept(f()), "f should be noexcept");
}
enum E1 { a };
enum E2 { b };
int main() {
int i = a | static_cast<int>(b);
}
Using a binary operation between an enumeration and a floating-point type is now a warning when the
/std:c++latest compiler option is enabled:
enum E1 { a };
int main() {
double i = a * 1.1;
}
enum E1 { a };
int main() {
double i = static_cast<int>(a) * 1.1;
}
int main() {
int a[] = { 1, 2, 3 };
int b[] = { 1, 2, 3 };
if (a == b) { return 1; }
}
To avoid the warning, you can compare the addresses of the first elements:
int main() {
int a[] = { 1, 2, 3 };
int b[] = { 1, 2, 3 };
if (&a[0] == &b[0]) { return 1; }
}
To determine whether the contents of two arrays are equal, use the std::equal function:
A definition of the spaceship operator ( <=> ) alone will no longer rewrite expressions involving == or != unless
the spaceship operator is marked as = default (P1185R2). The following example compiles in Visual Studio
2019 RTW and version 16.1, but produces C2678 in Visual Studio 2019 version 16.2:
#include <compare>
struct S {
int a;
auto operator<=>(const S& rhs) const {
return a <=> rhs.a;
}
};
bool eq(const S& lhs, const S& rhs) {
return lhs == rhs;
}
bool neq(const S& lhs, const S& rhs) {
return lhs != rhs;
}
#include <compare>
struct S {
int a;
auto operator<=>(const S& rhs) const {
return a <=> rhs.a;
}
bool operator==(const S&) const = default;
};
bool eq(const S& lhs, const S& rhs) {
return lhs == rhs;
}
bool neq(const S& lhs, const S& rhs) {
return lhs != rhs;
}
char x[42];
char* p = x;
std::cin >> std::setw(42);
std::cin >> p;
To avoid the error, use the extraction operator with a char[] variable:
char x[42];
std::cin >> x;
New keywords requires and concept have been added to the Microsoft C++ compiler. If you attempt to use
either one as an identifier in /std:c++latest mode, the compiler will raise C2059: syntax error .
Constructors as type names disallowed
The compiler no longer considers constructor names as injected-class-names in this case: when they appear in a
qualified name after an alias to a class-template specialization. Previously, constructors were usable as a type
name to declare other entities. The following example now produces C3646:
'TotalDuration': unknown override specifier :
#include <chrono>
class Foo {
std::chrono::milliseconds::duration TotalDuration{};
};
#include <chrono>
class Foo {
std::chrono::milliseconds TotalDuration {};
};
namespace N
{
extern "C" void f(int, int, int, bool);
}
void g()
{
N::f(0, 1, 2, false);
}
To avoid the errors in the previous example, use bool instead of BOOL consistently in both declarations of f .
Standard Library improvements
The non-standard headers <stdexcpt.h> and <typeinfo.h> have been removed. Code that includes them should
instead include the standard headers <exception> and <typeinfo>, respectively.
Two-phase name lookup requires that non-dependent names used in template bodies must be visible to the
template at definition time. Previously, such names may have been found when the template is instantiated. This
change makes it easier to write portable and conforming code in MSVC under the /permissive- flag.
In Visual Studio 2019 version 16.4 with the /permissive- flag set, the following example produces an error,
because N::f isn't visible when the f<T> template is defined:
namespace N {
int f() { return 42; }
}
Typically, this error can be fixed by including missing headers or forward-declaring functions or variables, as
shown in the following example:
namespace N {
int f();
}
namespace N {
int f() { return 42; }
}
int* f(bool* p) {
p = false; // error C2440: '=': cannot convert from 'bool' to 'bool *'
p = 0; // OK
return false; // error C2440: 'return': cannot convert from 'bool' to 'int *'
}
To fix the error, use nullptr instead of false . A literal 0 is still allowed:
int* f(bool* p) {
p = nullptr; // OK
p = 0; // OK
return nullptr; // OK
}
void f(int r) {
int i = 2964557531; // warning C4309: truncation of constant value
long long j = 0x8000000000000000ll >> r; // literal is now unsigned, shift will fill high-order bits with
0
}
The following example demonstrates how to keep the old behavior and avoid the warnings and run-time
behavior change:
void f(int r) {
int i = 2964557531u; // OK
long long j = (long long)0x8000000000000000ll >> r; // shift will keep high-order bits
}
template<typename T>
void f(T* buffer, int size, int& size_read);
template<typename T>
void f(T* buffer, int size, int& size_read);
#include <type_traits>
struct S;
template<>
struct std::is_fundamental<S> : std::true_type {};
static_assert(std::is_fundamental<S>::value, "fail");
To avoid the error, define a struct that inherits from the preferred type_trait , and specialize that:
#include <type_traits>
struct S;
template<typename T>
struct my_is_fundamental : std::is_fundamental<T> {};
template<>
struct my_is_fundamental<S> : std::true_type { };
static_assert(my_is_fundamental<S>::value, "fail");
The compiler no longer rewrites expressions using operator== if they involve a return type that isn't a bool . The
following code now produces error C2088: '!=': illegal for struct :
struct U {
operator bool() const;
};
struct S {
U operator==(const S&) const;
};
struct U {
operator bool() const;
};
struct S {
U operator==(const S&) const;
U operator!=(const S&) const;
};
The compiler no longer defines a defaulted comparison operator if it's a member of a union-like class. The
following example now produces error C2120: 'void' illegal with all types :
#include <compare>
union S {
int a;
char b;
auto operator<=>(const S&) const = default;
};
#include <compare>
union S {
int a;
char b;
auto operator<=>(const S&) const { ... }
};
The compiler will no longer define a defaulted comparison operator if the class contains a reference member. The
following code now produces error C2120: 'void' illegal with all types :
#include <compare>
struct U {
int& a;
auto operator<=>(const U&) const = default;
};
struct U {
int& a;
auto operator<=>(const U&) const { ... };
};
// In permissive-, this declaration isn't a definition, and the program won't link.
template <> int S<char>::a;
int main() {
return S<char>::a;
}
error LNK2019: unresolved external symbol "public: static int S<char>::a" (?a@?$S@D@@2HA) referenced in
function _main
at link time.
int main() {
return S<char>::a;
}
line line
#line 2
line
line
import // Invalid
m;
import m; // OK
#include <compare>
struct S {
std::strong_equality operator<=>(const S&) const = default;
};
void f() {
nullptr<=>nullptr;
&f <=> &f;
&S::operator<=> <=> &S::operator<=>;
}
To resolve the issue, update to prefer the built-in relational operators and replace the removed types:
#include <compare>
struct S {
std::strong_ordering operator<=>(const S&) const = default; // prefer 'std::strong_ordering'
};
void f() {
nullptr != nullptr; // use pre-existing builtin operator != or ==.
&f != &f;
&S::operator<=> != &S::operator<=>;
}
struct S {
S() = delete;
S(int) { }
};
struct U {
U() = delete;
U(int i): s{ i } { }
S s{};
};
U u{ 0 };
error C2280: 'S::S(void)': attempting to reference a deleted function
note: see declaration of 'S::S'
note: 'S::S(void)': function was explicitly deleted
struct S {
S() = delete;
S(int) { }
};
struct U {
U() = delete;
U(int i): s{ i } { }
U u{ 0 };
#include <iostream>
int main() {
const wchar_t cw = L'x', *pw = L"meow";
const char16_t c16 = u'x', *p16 = u"meow";
const char32_t c32 = U'x', *p32 = U"meow";
std::cout << cw << ' ' << pw << '\n';
std::cout << c16 << ' ' << p16 << '\n';
std::cout << c32 << ' ' << p32 << '\n';
std::wcout << c16 << ' ' << p16 << '\n';
std::wcout << c32 << ' ' << p32 << '\n';
}
You can achieve the effect of the old behavior in all language modes by converting character types to
unsigned int , or pointer-to-character types to const void* :
#include <iostream>
int main() {
const wchar_t cw = L'x', *pw = L"meow";
const char16_t c16 = u'x', *p16 = u"meow";
const char32_t c32 = U'x', *p32 = U"meow";
std::cout << (unsigned)cw << ' ' << (const void*)pw << '\n'; // Outputs "120 0052B1C0"
std::cout << (unsigned)c16 << ' ' << (const void*)p16 << '\n'; // Outputs "120 0052B1CC"
std::cout << (unsigned)c32 << ' ' << (const void*)p32 << '\n'; // Outputs "120 0052B1D8"
std::wcout << (unsigned)c16 << ' ' << (const void*)p16 << '\n'; // Outputs "120 0052B1CC"
std::wcout << (unsigned)c32 << ' ' << (const void*)p32 << '\n'; // Outputs "120 0052B1D8"
}
Previously, the MSVC implementation of the promotion rules for the return type of function template std::pow()
was incorrect. For example, previously pow(complex<float>, int) returned complex<float> . Now it correctly
returns complex<double> . The fix has been implemented unconditionally for all standards modes in Visual Studio
2019 version 16.6.
This change can cause compiler errors. For example, previously you could multiply pow(complex<float>, int) by
a float . Because complex<T> operator* expects arguments of the same type, the following example now emits
compiler error C2676:
binary '*': 'std::complex<double>' does not define this operator or a conversion to a type acceptable to the
predefined operator
:
// pow_error.cpp
// compile by using: cl /EHsc /nologo /W4 pow_error.cpp
#include <complex>
int main() {
std::complex<float> cf(2.0f, 0.0f);
(void) (std::pow(cf, -1) * 3.0f);
}
Narrow the result of pow to complex<float> by saying complex<float>{pow(ARG, ARG)} . Then you can
continue to multiply by a float value.
Pass float instead of int to pow . This operation may be slower.
In some cases, you can avoid pow entirely. For example, pow(cf, -1) can be replaced by division.
Switch-related warnings for C
Starting in Visual Studio 2019 version 16.6, the compiler implements some preexisting C++ warnings for code
compiled as C. The following warnings are now enabled at different levels: C4060, C4061, C4062, C4063, C4064,
C4065, C4808, and C4809. Warnings C4065 and C4060 are disabled by default in C.
The warnings trigger on missing case statements, undefined enum , and bad bool switches (that is, ones that
contain too many cases). For example:
#include <stdbool.h>
int main() {
bool b = true;
switch (b) {
case true: break;
case false: break;
default: break; // C4809: switch statement has redundant 'default' label;
// all possible 'case' labels are given
}
}
#include <stdbool.h>
int main() {
bool b = true;
switch (b) {
case true: break;
case false: break;
}
}
The code above can be fixed by giving the unnamed class a name:
struct B { };
typedef struct S_ : B {
void f();
static int i;
struct U {
void f();
};
int j = 10;
} S;
public class R {
public void Func(string s) {} // overload 1
public void Func(string s, string s2 = "") {} // overload 2;
}
When this class is imported into C++/CLI, a call to one of the overloads causes an error:
The compiler emits error C2668 because both overloads match this argument list. In the second overload, the
second argument is filled in by the default argument. To work around this problem, you can delete the redundant
overload (1). Or, use the full argument list and explicitly supply the default arguments.
struct S
{
volatile int m;
};
static_assert(std::is_trivially_copyable_v<S>, "Meow!");
This code doesn't compile in versions of MSVC before Visual Studio 2019 version 16.7. There's an off-by-default
compiler warning that you can use to detect this change. If you compile the code above by using cl /W4 /w45220 ,
you'll see the following warning:
warning C5220:
'S::m': a non-static data member with a volatile qualified type no longer implies that compiler generated
copy/move constructors and copy/move assignment operators are non trivial
struct X { bool b; };
void f(X);
int main() {
f(X { "whoops?" }); // error: conversion from 'const char [8]' to 'bool' requires a narrowing conversion
To correct this code, either add explicit comparisons to nullptr , or avoid contexts where narrowing conversions
are ill-formed:
struct X { bool b; };
void f(X);
int main() {
f(X { "whoops?" != nullptr }); // Absurd, but OK
int main() {
bool b1 = nullptr; // error: cannot convert from 'nullptr' to 'bool'
S s { nullptr }; // error: cannot convert from 'nullptr' to 'bool'
g(nullptr); // error: cannot convert argument 1 from 'nullptr' to 'bool'
struct B {
explicit B() {}
};
void f() {
B b1[1]{}; // Error in /permissive-, because aggregate init calls explicit ctor
B b2[1]; // OK: calls default ctor for each array element
}
S f();
void g()
{
auto p1 = &(f()); // The temporary returned by 'f' is destructed after this statement. So 'p1' points to
an invalid object.
const auto &r = f(); // This extends the lifetime of the temporary returned by 'f'
auto p2 = &r; // 'p2' points to a valid object
}
// common.h
struct S {
template<typename T> void f(T);
template<> void f(int);
};
// a.cpp
#include "common.h"
int main() {}
// b.cpp
#include "common.h"
template<typename T>
int compare(T x, T y)
{
return x < y ? -1 : (x > y ? 1 : 0);
}
Previously, the call to compare would have attempted to specialize the function template compare with the
template argument for T being String . It would fail to generate a valid specialization, because String is an
abstract class. The only viable candidate would have been compare(const Node&, const Node&) . However, under
C++20 the check for the abstract class type doesn't happen until the function is called. So, the specialization
compare(String, String) gets added to the set of viable candidates, and it's chosen as the best candidate because
the conversion from const String& to String is a better conversion sequence than the conversion from
const String& to const Node& .
Under C++20, one possible fix for this example is to use concepts; that is, change the definition of compare to:
template<typename T>
int compare(T x, T y) requires !std::is_abstract_v<T>
{
return x < y ? -1 : (x > y ? 1 : 0);
}
Or, if C++ concepts aren't available, you can fall back to SFINAE:
Support for P0960R3 - allow initializing aggregates from a parenthesized list of values
C++20 adds support for initializing an aggregate using a parenthesized initializer-list. For example, the following
code is valid in C++20:
struct S {
int i;
int j;
};
S s(1, 2);
Most of this feature is additive, that is, code now compiles that didn't compile before. However, it does change the
behavior of std::is_constructible . In C++17 mode this static_assert fails, but in C++20 mode it succeeds:
static_assert(std::is_constructible_v<S, int, int>, "Assertion failed!");
If this type-trait is used to control overload resolution, it can lead to a change in behavior between C++17 and
C++20.
Overload resolution involving function templates
Previously, the compiler allowed some code to compile under /permissive- that shouldn't compile. The effect
was, the compiler called the wrong function leading to a change in runtime behavior:
int f(int);
namespace N
{
using ::f;
template<typename T>
T f(T);
}
template<typename T>
void g(T&& t)
{
}
void h()
{
using namespace N;
g(f);
}
The call to g uses an overload set that contains two functions, ::f and N::f . Since N::f is a function
template, the compiler should treat the function argument as a non-deduced context. It means that, in this case,
the call to g should fail, as the compiler can't deduce a type for the template parameter T . Unfortunately, the
compiler didn't discard the fact that it had already decided that ::f was a good match for the function call.
Instead of emitting an error, the compiler would generate code to call g using ::f as the argument.
Given that in many cases using ::f as the function argument is what the user expects, we only emit an error if
the code is compiled with /permissive- .
Migrating from /await to C++20 coroutines
Standard C++20 coroutines are now on by default under /std:c++latest . They differ from the Coroutines TS and
the support under the /await switch. Migrating from /await to standard coroutines may require some source
changes.
Non-standard keywords
The old await and yield keywords aren't supported in C++20 mode. Code must use co_await and co_yield
instead. Standard mode also doesn't allow the use of return in a coroutine. Every return in a coroutine must
use co_return .
// /await
task f_legacy() {
...
await g();
return n;
}
// /std:c++latest
task f() {
...
co_await g();
co_return n;
}
Types of initial_suspend/final_suspend
Under /await , the promise initial and suspend functions may be declared as returning bool . This behavior isn't
standard. In C++20, these functions must return an awaitable class type, often one of the trivial awaitables
std::suspend_always if the function previously returned true or std::suspend_never if it returned false .
// /await
struct promise_type_legacy {
bool initial_suspend() noexcept { return false; }
bool final_suspend() noexcept { return true; }
...
};
// /std:c++latest
struct promise_type {
auto initial_susepend() noexcept { return std::suspend_never{}; }
auto final_suspend() noexcept { return std::suspend_always{}; }
...
};
Type of yield_value
In C++20, the promise yield_value function must return an awaitable. In /await mode, the yield_value
function was permitted to return void , and would always suspend. Such functions can be replaced with a
function that returns std::suspend_always .
// /await
struct promise_type_legacy {
...
void yield_value(int x) { next = x; };
};
// /std:c++latest
struct promise_type {
...
auto yield_value(int x) { next = x; return std::suspend_always{}; }
};
// /await
auto my_generator() {
...
co_yield next;
};
// /std:c++latest
#include <experimental/generator>
std::experimental::generator<int> my_generator() {
...
co_yield next;
};
The return type of the promise return_value function must be void . In /await mode, the return type can be
anything, and is ignored. This diagnostic can help detect subtle errors where the author incorrectly assumes the
return value of return_value is returned to a caller.
// /await
struct promise_type_legacy {
...
int return_value(int x) { return x; } // incorrect, the return value of this function is unused and the
value is lost.
};
// /std:c++latest
struct promise_type {
...
void return_value(int x) { value = x; }; // save return value
};
struct coro {
struct promise_type {
promise_type() { ... }
promise_type(int x) { ... }
...
};
};
// Under /await the promise gets constructed using the default constructor.
// Under /std:c++latest the promise gets constructed using the 1-argument constructor.
f1(0);
struct Object {
template <typename T> operator T() { ... } // Converts to anything!
};
// Under /await the promise gets constructed using the default constructor
// Under /std:c++latest the promise gets copy- or move-constructed from the result of
// Object::operator coro::promise_type().
f2(Object{});
C++20 Modules support is on by default under /std:c++latest . For more information about this change, and
the scenarios where module and import are conditionally treated as keywords, see Standard C++20 Modules
support with MSVC in Visual Studio 2019 version 16.8.
As a prerequisite for Modules support, permissive- is now enabled when /std:c++latest is specified. For more
information, see /permissive- .
For code that previously compiled under /std:c++latest and requires non-conforming compiler behaviors,
permissive may be specified to turn off strict conformance mode in the compiler. The compiler option must
appear after /std:c++latest in the command-line argument list. However, permissive results in an error if
Modules usage is encountered:
error C1214: Modules conflict with non-standard behavior requested via 'option'
O P T IO N DESC RIP T IO N
/Zc:twoPhase- Two Phase name lookup is required for C++20 Modules and
implied by permissive- .
long long i = 0;
constexpr void f() {
int* a = reinterpret_cast<int*>(i);
}
To avoid the error, remove the constexpr modifier from the function declaration.
Correct diagnostics for basic_string range constructor
In Visual Studio 2019, the basic_string range constructor no longer suppresses compiler diagnostics with
static_cast . The following code compiles without warnings in Visual Studio 2017, despite the possible loss of
data from wchar_t to char when initializing out :
std::wstring ws = /* … */;
std::string out(ws.begin(), ws.end());
Incorrect calls to += and -= under /clr or /ZW are now correctly detected
A bug was introduced in Visual Studio 2017 that caused the compiler to silently ignore errors and generate no
code for the invalid calls to += and -= under /clr or /ZW . The following code compiles without errors in
Visual Studio 2017 but in Visual Studio 2019 it correctly raises error C2845:
'System::String ^': pointer arithmetic not allowed on this type :
struct X
{
private:
static inline const int c = 1000;
};
struct Y : X
{
static inline int d = c; // C2248 in Visual Studio 2019
};
struct X
{
protected:
static inline const int c = 1000;
};
C4800 reinstated
MSVC used to have a performance warning C4800 about implicit conversion to bool . It was too noisy and
couldn't be suppressed, leading us to remove it in Visual Studio 2017. However, over the lifecycle of Visual Studio
2017 we got lots of feedback on the useful cases it was solving. We bring back in Visual Studio 2019 a carefully
tailored C4800, along with the explanatory C4165. Both of these warnings are easy to suppress: either by using
an explicit cast, or by comparison to 0 of the appropriate type. C4800 is an off-by-default level 4 warning, and
C4165 is an off-by-default level 3 warning. Both are discoverable by using the /Wall compiler option.
The following example raises C4800 and C4165 under /Wall :
bool test(IUnknown* p)
{
bool valid = p; // warning C4800: Implicit conversion from 'IUnknown*' to bool. Possible information loss
IDispatch* d = nullptr;
HRESULT hr = p->QueryInterface(__uuidof(IDispatch), reinterpret_cast<void**>(&d));
return hr; // warning C4165: 'HRESULT' is being converted to 'bool'; are you sure this is what you want?
}
To avoid the warnings in the previous example, you can write the code like this:
bool test(IUnknown* p)
{
bool valid = p != nullptr; // OK
IDispatch* d = nullptr;
HRESULT hr = p->QueryInterface(__uuidof(IDispatch), reinterpret_cast<void**>(&d));
return SUCCEEDED(hr); // OK
}
void example()
{
struct A
{
int boo(); // warning C4822
};
}
int f()
{
T::Type a; // error C7510
if constexpr (T::val)
{
return 1;
}
else
{
return 2;
}
}
struct X
{
using Type = X;
constexpr static int val = 1;
};
int main()
{
return f<X>();
}
To avoid the error, add the typename keyword to the declaration of a : typename T::Type a; .
Inline assembly code isn't supported in a lambda expression
The Microsoft C++ team was recently made aware of a security issue in which the use of inline-assembler within
a lambda could lead to the corruption of ebp (the return address register) at runtime. A malicious attacker could
possibly take advantage of this scenario. The inline assembler is only supported on x86, and interaction between
the inline assembler and the rest of the compiler is poor. Given these facts and the nature of the issue, the safest
solution to this problem was to disallow inline assembler within a lambda expression.
The only use of inline assembler within a lambda expression that we have found 'in the wild' was to capture the
return address. In this scenario, you can capture the return address on all platforms simply by using a compiler
intrinsic _ReturnAddress() .
The following code produces C7552: inline assembler is not supported in a lambda in both Visual Studio 2017
15.9 and in Visual Studio 2019:
#include <cstdio>
int f()
{
int y = 1724;
int x = 0xdeadbeef;
mov eax, x
mov y, eax
}
};
lambda();
return y;
}
To avoid the error, move the assembly code into a named function as shown in the following example:
#include <cstdio>
int f()
{
int y = 1724;
int x = 0xdeadbeef;
auto lambda = [&]
{
g(x, y);
};
lambda();
return y;
}
int main()
{
std::printf("%d\n", f());
}
The iterator debugging feature has been taught to properly unwrap std::move_iterator . For example,
std::copy(std::move_iterator<std::vector<int>::iterator>, std::move_iterator<std::vector<int>::iterator>,
int*)
can now engage the memcpy fast path.
Fixes for <xkeycheck.h> keyword enforcement
The standard library's enforcement in <xkeycheck.h> for macros replacing a keyword was fixed. The library now
emits the actual problem keyword detected rather than a generic message. It also supports C++20 keywords,
and avoids tricking IntelliSense into saying random keywords are macros.
Allocator types no longer deprecated
std::allocator<void> , std::allocator::size_type , and std::allocator::difference_type are no longer
deprecated.
Correct warning for narrowing string conversions
Removed a spurious static_cast from std::string that wasn't called for by the standard, and that accidentally
suppressed C4244 narrowing warnings. Attempts to call std::string::string(const wchar_t*, const wchar_t*)
now properly emit C4244 narrowing a wchar_t into a char .
Various fixes for <filesystem> correctness
Fixed std::filesystem::last_write_time failing when attempting to change a directory's last write time.
The std::filesystem::directory_entry constructor now stores a failed result, rather than throwing an
exception, when supplied a nonexistent target path.
The std::filesystem::create_directory 2-parameter version was changed to call the 1-parameter version, as
the underlying CreateDirectoryExW function would use copy_symlink when the existing_p was a symlink.
std::filesystem::directory_iterator no longer fails when a broken symlink is found.
std::filesystem::space now accepts relative paths.
std::filesystem::path::lexically_relative is no longer confused by trailing slashes, reported as LWG 3096.
Worked around CreateSymbolicLinkW rejecting paths with forward slashes in
std::filesystem::create_symlink .
Worked around the POSIX deletion mode delete function that existed in Windows 10 LTSB 1609, but
couldn't actually delete files.
std::boyer_moore_searcher and std::boyer_moore_horspool_searcher 's copy constructors and copy assignment
operators now actually copy things.
Parallel algorithms on Windows 8 and later
The parallel algorithms library now properly uses the real WaitOnAddress family on Windows 8 and later, rather
than always using the Windows 7 and earlier fake versions.
std::system_category::message() whitespace
std::system_category::message() now trims trailing whitespace from the returned message.
std::linear_congruential_engine divide by zero
Some conditions that would cause std::linear_congruential_engine to trigger divide by 0 have been fixed.
Fixes for iterator unwrapping
Some iterator-unwrapping machinery was first exposed for programmer-user integration in Visual Studio 2017
15.8. It was described in C++ Team Blog article STL Features and Fixes in VS 2017 15.8. This machinery no longer
unwraps iterators derived from standard library iterators. For example, a user that derives from
std::vector<int>::iterator and tries to customize behavior now gets their customized behavior when calling
standard library algorithms, rather than the behavior of a pointer.
The unordered container reserve function now actually reserves for N elements, as described in LWG 2156.
Time handling
Previously, some time values that were passed to the concurrency library would overflow, for example,
condition_variable::wait_for(seconds::max()) . Now fixed, the overflows changed behavior on a seemingly
random 29-day cycle (when uint32_t milliseconds accepted by underlying Win32 APIs overflowed).
The <ctime> header now correctly declares timespec and timespec_get in namespace std , and also
declares them in the global namespace.
Various fixes for containers
Many standard library internal container functions have been made private for an improved IntelliSense
experience. Additional fixes to mark members as private are expected in later releases of MSVC.
Exception safety correctness problems wherein the node-based containers like list , map , and
unordered_map would become corrupted were fixed. During a propagate_on_container_copy_assignment or
propagate_on_container_move_assignment reassignment operation, we would free the container's sentinel
node with the old allocator, do the POCCA/POCMA assignment over the old allocator, and then try to
acquire the sentinel node from the new allocator. If this allocation failed, the container was corrupted. It
couldn't even be destroyed, as owning a sentinel node is a hard data structure invariant. This code was
fixed to create the new sentinel node by using the source container's allocator before destroying the
existing sentinel node.
The containers were fixed to always copy/move/swap allocators according to
propagate_on_container_copy_assignment , propagate_on_container_move_assignment , and
propagate_on_container_swap , even for allocators declared is_always_equal .
Added the overloads for container merge and extract member functions that accept rvalue containers. For
more information, see P0083 "Splicing Maps And Sets"
std::basic_istream::read processing of \r\n`` => \n`
std::basic_istream::read was fixed to not write into parts of the supplied buffer temporarily as part of \r\n =>
\n processing. This change gives up some of the performance advantage that was gained in Visual Studio 2017
15.8 for reads larger than 4K in size. However, efficiency improvements from avoiding three virtual calls per
character are still present.
std::bitset constructor
The std::bitset constructor no longer reads the ones and zeroes in reverse order for large bitsets.
std::pair::operator= regression
Fixed a regression in std::pair 's assignment operator introduced when implementing LWG 2729 "Missing
SFINAE on std::pair::operator=";. It now correctly accepts types convertible to std::pair again.
Non-deduced contexts for add_const_t
Fixed a minor type traits bug, where add_const_t and related functions are supposed to be a non-deduced
context. In other words, add_const_t should be an alias for typename add_const<T>::type , not const T .
struct K
{
int a;
string b = "label";
};
struct Comparer {
bool operator() (K a, K b) {
return a.a < b.a;
}
};
K const s1{1};
K const s2{2};
K const s3{3};
int main() {
m.emplace(s1, 1.08);
m.emplace(s2, 3.14);
m.emplace(s3, 5.21);
struct Comparer {
bool operator() (K a, K b) const {
return a.a < b.a;
}
};
Bug fixes and behavior changes in Visual Studio 2019 version 16.7
Initialization of class members with overloaded names is correctly sequenced
We identified a bug in class data members' internal representation when a type name is also overloaded as a
data member's name. This bug caused inconsistencies in aggregate initialization and member initialization order.
The generated initialization code is now correct. However, this change can lead to errors or warnings in source
that inadvertently relied on the mis-ordered members, as in this example:
In previous versions, the constructor would incorrectly initialize the data member Inner before the data member
v . (The C++ standard requires an initialization order that's the same as the declaration order of the members).
Now that the generated code follows the standard, the member-init-list is out of order. The compiler generates a
warning for this example. To fix it, reorder the member-initializer-list to reflect the declaration order.
Overload resolution involving integral overloads and long arguments
The C++ standard requires ranking a long to int conversion as a standard conversion. Previous MSVC
compilers incorrectly rank it as an integral promotion, which ranks higher for overload resolution. This ranking
can cause overload resolution to resolve successfully when it should be considered ambiguous.
The compiler now considers the rank correctly in /permissive- mode. Invalid code gets diagnosed properly, as in
this example:
int main() {
long x {};
f(x); // error: 'f': ambiguous call to overloaded function
f(static_cast<int>(x)); // OK
}
namespace {
extern int x; // Not a definition, but has internal linkage because of the anonymous namespace
}
int main()
{
return x; // Use of 'x' that no other translation unit can possibly define.
}
This program previously incorrectly compiled and linked, but will now emit:
error C7631: 'anonymous-namespace'::x': variable with internal linkage declared but not defined
Such variables must be defined in the same translation unit they're used in. For example, you can provide an
explicit initializer or a separate definition.
Type completeness and derived-to -base pointer conversions
In C++ standards before C++20, a conversion from a derived class to a base class didn't require the derived class
to be a complete class type. The C++ standard committee has approved a retroactive Defect Report change that
applies to all versions of the C++ language. This change aligns the conversion process with type traits, such as
std::is_base_of , which do require that the derived class is a complete class type.
Here's an example:
template<typename A, typename B>
struct check_derived_from
{
static A a;
static constexpr B* p = &a;
};
struct W { };
struct X { };
struct Y { };
// With this change this code will fail as Z1 is not a complete class type
struct Z1 : X, check_derived_from<Z1, X>
{
};
// This code failed before and it will still fail after this change
struct Z2 : check_derived_from<Z2, Y>, Y
{
};
// With this change this code will fail as Z3 is not a complete class type
struct Z3 : W
{
check_derived_from<Z3, W> cdf;
};
This behavior change applies to all C++ language modes of MSVC, not just /std:c++latest .
Narrowing conversions are more consistently diagnosed
MSVC emits a warning for narrowing conversions in a braced-list initializer. Previously, the compiler wouldn't
diagnose narrowing conversions from larger enum underlying types to narrower integral types. (The compiler
incorrectly considered them an integral promotion instead of a conversion). If the narrowing conversion is
intentional, you can avoid the warning by using a static_cast on the initializer argument. Or, choose a larger
destination integral type.
Here's an example of using an explicit static_cast to address the warning:
void f(E e) {
S s = { e }; // warning: conversion from 'E' to 'int' requires a narrowing conversion
S s1 = { static_cast<int>(e) }; // Suppress warning with explicit conversion
}
Expressions declared as constexpr are now allowed to contain certain kinds of declarations, if and switch
statements, loop statements, and mutation of objects whose lifetime began within the constexpr expression
evaluation. There's no longer a requirement that a constexpr non-static member function must be implicitly
const . For more information, see Relaxing constraints on constexpr functions.
the message parameter for static_assert is optional. For more information, see Extending static_assert, v2.
C++17: [[fallthrough]] attribute
In /std:c++17 mode, the [[fallthrough]] attribute can be used in the context of switch statements as a hint to
the compiler that the fall-through behavior is intended. This attribute prevents the compiler from issuing
warnings in such cases. For more information, see Wording for [[fallthrough]] attribute.
Generalized range -based for loops
Range-based for loops no longer require that begin() and end() return objects of the same type. This change
enables end() to return a sentinel as used by ranges in range-v3 and the completed-but-not-quite-published
Ranges Technical Specification. For more information, see Generalizing the Range-Based for Loop.
operator++ is no longer supported on bool types. For more information, see Remove Deprecated operator++
(bool).
Removing deprecated register keyword
The register keyword, previously deprecated (and ignored by the compiler), is now removed from the
language. For more information, see Remove Deprecated Use of the register Keyword.
In earlier versions of Visual Studio, the compiler always gave a constexpr variable internal linkage, even when
the variable was marked extern . In Visual Studio 2017 version 15.5, a new compiler switch, /Zc:externConstexpr
, enables correct and standards-conforming behavior. For more information, see extern constexpr linkage.
Removing dynamic exception specifications
P0003R5 Dynamic exception specifications were deprecated in C++11. the feature is removed from C++17, but
the (still) deprecated throw() specification is kept strictly as an alias for noexcept(true) . For more information,
see Dynamic exception specification removal and noexcept.
not_fn()
P0033R1 enable_shared_from_this was added in C++11. The C++17 standard updates the specification to better
handle certain corner cases. [14]
Splicing maps and sets
P0083R3 This feature enables extraction of nodes from associative containers (that is, map , set , unordered_map ,
unordered_set ) which can then be modified and inserted back into the same container or a different container
that uses the same node type. (A common use case is to extract a node from a std::map , change the key, and
reinsert.)
Deprecating vestigial library parts
P0174R2 Several features of the C++ standard library have been superseded by newer features over the years,
or else have been found not useful, or problematic. These features are officially deprecated in C++17.
Removing allocator support in std::function
P0302R1 Prior to C++17, the class template std::function had several constructors that took an allocator
argument. However, the use of allocators in this context was problematic, and the semantics were unclear. The
problem contructors have been removed.
Fixes for not_fn()
P0358R1 New wording for std::not_fn provides support of propagation of value category when used in
wrapper invocation.
shared_ptr<T[]> , shared_ptr<T[N]>
P0508R0 The associative containers with unique keys, and the unordered containers with unique keys have a
member function insert that returns a nested type insert_return_type . That return type is now defined as a
specialization of a type that is parameterized on the Iterator and NodeType of the container.
Inline variables for the standard library
P0607R0
Annex D features deprecated
Annex D of the C++ standard contains all the features that have been deprecated, including
shared_ptr::unique() , <codecvt> , and namespace std::tr1 . When the /std:c++17 compiler switch is set, almost
all the standard library features in Annex D are marked as deprecated. For more information, see Standard library
features in Annex D are marked as deprecated.
The std::tr2::sys namespace in <experimental/filesystem> now emits a deprecation warning under
/std:c++14 by default, and is now removed under /std:c++17 by default.
Improved conformance in <iostream> by avoiding a non-standard extension (in-class explicit specializations).
The standard library now uses variable templates internally.
The standard library was updated in response to C++17 compiler changes. Updates include the addition of
noexcept in the type system, and the removal of dynamic-exception-specifications.
struct A {
template<typename T>
A(T, typename T::type = 0);
A(int);
};
struct B : A {
using A::A;
B(int n) = delete; // Error C2280
};
struct A {
template<typename T>
A(T, typename T::type = 0);
A(int);
};
struct B : A {
using A::A;
B(int n)
{
//do something
}
};
struct Derived;
struct Base {
friend struct Derived;
private:
Base() {}
};
In C++17, Derived is now considered an aggregate type. It means that the initialization of Base via the private
default constructor happens directly, as part of the extended aggregate initialization rule. Previously, the Base
private constructor was called via the Derived constructor, and it succeeded because of the friend declaration.
The following example shows C++17 behavior in Visual Studio version 15.7 in /std:c++17 mode:
struct Derived;
struct Base {
friend struct Derived;
private:
Base() {}
};
struct Derived : Base {
Derived() {} // add user-defined constructor
// to call with {} initialization
};
Derived d1; // OK. No aggregate init involved.
Derived d2 {}; // error C2248: 'Base::Base': cannot access
// private member declared in class 'Base'
One impact of this new feature is that valid C++14 code may not be valid or may have different semantics. For
example, some overloads that were previously invalid are now valid. The following example shows C++14 code
that compiles because the call to example(p) is bound to example(void*); . In Visual Studio 2017 version 15.7, in
/std:c++17 mode, the example function template is the best match.
The following example shows C++17 code in Visual Studio 15.7 in /std:c++17 mode:
P0030R1 Adds three new overloads to std::hypot , for types float , double , and long double , each of which
has three input parameters.
C++17: <filesystem>
P0218R1 Adopts the File System TS into the standard with a few wording modifications.
C++17: Mathematical special functions
P0226R1 Adopts previous technical specifications for Mathematical Special Functions into the standard <cmath>
header.
C++17: Deduction guides for the standard library
P0433R2 Updates to STL to take advantage of C++17 adoption of P0091R3, which adds support for class
template argument deduction.
C++17: Repairing elementary string conversions
P0682R1 Move the new elementary string conversion functions from P0067R5 into a new header <charconv>
and make other improvements, including changing error handling to use std::errc instead of std::error_code .
C++17: constexpr for char_traits (partial)
P0426R1 Changes to std::traits_type member functions length , compare , and find to make
std::string_view usable in constant expressions. (In Visual Studio 2017 version 15.6, supported for Clang/LLVM
only. In version 15.7 Preview 2, support is nearly complete for ClXX as well.)
Starting in C++17, the operands of the operators ->* , [] , >> , and << must be evaluated in left-to-right order.
There are two cases in which the compiler is unable to guarantee this order:
when one of the operand expressions is an object passed by value or contains an object passed by value,
or
when compiled by using /clr , and one of the operands is a field of an object or an array element.
The compiler emits warning C4866 when it can't guarantee left-to-right evaluation. The compiler generates this
warning only if /std:c++17 or later is specified, as the left-to-right order requirement of these operators was
introduced in C++17.
To resolve this warning, first consider whether left-to-right evaluation of the operands is necessary. For example,
it could be necessary when evaluation of the operands might produce order-dependent side-effects. The order in
which operands are evaluated has no observable effect in many cases. If the order of evaluation must be left-to-
right, consider whether you can pass the operands by const reference instead. This change eliminates the
warning in the following code sample:
// C4866.cpp
// compile with: /w14866 /std:c++17
class HasCopyConstructor
{
public:
int x;
HasCopyConstructor(int x) : x(x) {}
HasCopyConstructor(const HasCopyConstructor& h) : x(h.x) { }
};
int main()
{
HasCopyConstructor a{ 1 };
HasCopyConstructor b{ 2 };
struct A
{
explicit A(int) {}
A(double) {}
};
int main()
{
A a1 = { 1 }; // error C3445: copy-list-initialization of 'A' cannot use an explicit constructor
const A& a2 = { 1 }; // error C2440: 'initializing': cannot convert from 'int' to 'const A &'
A a1{ 1 };
const A& a2{ 1 };
In Visual Studio 2015, the compiler erroneously treated copy-list-initialization in the same way as regular copy-
initialization: it considered only converting constructors for overload resolution. In the following example, Visual
Studio 2015 chooses MyInt(23) . Visual Studio 2017 correctly raises the error.
// From http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1228
struct MyStore {
explicit MyStore(int initialCapacity);
};
struct MyInt {
MyInt(int i);
};
struct Printer {
void operator()(MyStore const& s);
void operator()(MyInt const& i);
};
void f() {
Printer p;
p({ 23 }); // C3066: there are multiple ways that an object of this type can be called with these
arguments
}
This example is similar to the previous one but raises a different error. It succeeds in Visual Studio 2015 and fails
in Visual Studio 2017 with C2668.
struct A {
explicit A(int) {}
};
struct B {
B(int) {}
};
int main()
{
f({ 1 }); // error C2668: 'f': ambiguous call to overloaded function
}
Deprecated typedefs
Visual Studio 2017 now issues the correct warning for deprecated typedefs declared in a class or struct. The
following example compiles without warnings in Visual Studio 2015. It produces C4996 in Visual Studio 2017.
struct A
{
// also for __declspec(deprecated)
[[deprecated]] typedef int inttype;
};
int main()
{
A::inttype a = 0; // C4996 'A::inttype': was declared deprecated
}
constexpr
Visual Studio 2017 correctly raises an error when the left-hand operand of a conditionally evaluating operation
isn't valid in a constexpr context. The following code compiles in Visual Studio 2015, but not in Visual Studio
2017, where it raises C3615 constexpr function 'f' cannot result in a constant expression :
template<int N>
struct array
{
int size() const { return N; }
};
To correct the error, either declare the array::size() function as constexpr or remove the constexpr qualifier
from f .
Class types passed to variadic functions
In Visual Studio 2017, classes or structs that are passed to a variadic function such as printf must be trivially
copyable. When passing such objects, the compiler simply makes a bitwise copy and doesn't call the constructor
or destructor.
#include <atomic>
#include <memory>
#include <stdio.h>
int main()
{
std::atomic<int> i(0);
printf("%i\n", i); // error C4839: non-standard use of class 'std::atomic<int>'
// as an argument to a variadic function.
// note: the constructor and destructor will not be called;
// a bitwise copy of the class will be passed as the argument
// error C2280: 'std::atomic<int>::atomic(const std::atomic<int> &)':
// attempting to reference a deleted function
struct S {
S(int i) : i(i) {}
S(const S& other) : i(other.i) {}
operator int() { return i; }
private:
int i;
} s(0);
printf("%i\n", s); // warning C4840 : non-portable use of class 'main::S'
// as an argument to a variadic function
}
To correct the error, you can call a member function that returns a trivially copyable type,
std::atomic<int> i(0);
printf("%i\n", i.load());
or else use a static cast to convert the object before passing it:
For strings built and managed using CString , the provided operator LPCTSTR() should be used to cast a
CString object to the C pointer expected by the format string.
CString str1;
CString str2 = _T("hello!");
str1.Format(_T("%s"), static_cast<LPCTSTR>(str2));
struct S
{
S(int);
operator int();
};
#include <type_traits>
int main()
{
f(10); // C2672: No matching overloaded function found.
}
#include <utility>
template <class T, class ReturnT, class... ArgsT>
class IsCallable
{
public:
struct BadType {};
value struct V
{
int i = 0; // error C3446: 'V::i': a default member initializer
// isn't allowed for a member of a value class
};
using System.Reflection;
using System.Runtime.InteropServices;
namespace ClassLibrary1
{
[DefaultMember("Value")]
public class Class1
{
public int Value
{
// using attribute on the return type triggers the compiler bug
[return: MarshalAs(UnmanagedType.I4)]
get;
}
}
[DefaultMember("Value")]
public class Class2
{
public int Value
{
get;
}
}
}
// code.cpp
#using "class1.dll"
In Visual Studio 2017, you can access both Value properties by their name:
#using "class1.dll"
void g()
{
decltype(S<int>::f<int>()) i; // this should fail
}
struct S;
enum E;
New compiler warning and runtime checks on native -to -managed marshaling
Calling from managed functions to native functions requires marshaling. The CLR does the marshaling, but it
doesn't understand C++ semantics. If you pass a native object by value, CLR either calls the object's copy-
constructor or uses BitBlt , which may cause undefined behavior at runtime.
Now the compiler emits a warning if it finds this error at compile time: a native object with deleted copy ctor gets
passed between a native and managed boundary by value. For those cases in which the compiler doesn't know at
compile time, it injects a runtime check so that the program calls std::terminate immediately when an ill-
formed marshaling occurs. In Visual Studio 2017 version 15.3, the following code produces warning C4606
'A': passing argument by value across native and managed boundary requires valid copy constructor. Otherwise,
the runtime behavior is undefined.
class A
{
public:
A() : p_(new int) {}
~A() { delete p_; }
private:
int *p_;
};
#pragma unmanaged
void f(A a)
{
}
#pragma managed
int main()
{
f(A()); // This call from managed to native requires marshaling. The CLR doesn't understand C++ and uses
BitBlt, which results in a double-free later.
}
To fix the error, remove the #pragma managed directive to mark the caller as native and avoid marshaling.
Experimental API warning for WinRT
WinRT APIs that are released for experimentation and feedback are decorated with
Windows.Foundation.Metadata.ExperimentalAttribute . In Visual Studio 2017 version 15.3, the compiler produces
warning C4698 for this attribute. A few APIs in previous versions of the Windows SDK have already been
decorated with the attribute, and calls to these APIs now trigger this compiler warning. Newer Windows SDKs
have the attribute removed from all shipped types. If you're using an older SDK, you'll need to suppress these
warnings for all calls to shipped types.
The following code produces warning C4698:
'Windows::Storage::IApplicationDataStatics2::GetForUserAsync' is for evaluation purposes only and is subject
to change or removal in future updates
:
Windows::Storage::IApplicationDataStatics2::GetForUserAsync(); //C4698
#pragma warning(push)
#pragma warning(disable:4698)
Windows::Storage::IApplicationDataStatics2::GetForUserAsync();
#pragma warning(pop)
struct S {
template <typename T>
void f(T t);
};
template <typename T>
void S::f(T t) {}
#include <memory>
class B { };
class D : B { }; // C2243. should be public B { };
void f()
{
std::unique_ptr<B>(new D());
}
struct A {
int arr[10];
};
To fix the code, either disable the warning with a pragma or change the code to not use offsetof :
#pragma warning(push)
#pragma warning(disable: 4841)
constexpr auto off = offsetof(A, arr[2]);
#pragma warning(pop)
#include <cstddef>
struct A {
int ten() { return 10; }
static constexpr int two = 2;
};
This code is ill-formed and could potentially cause a crash at runtime. To fix the error, change the code to no
longer invoke undefined behavior. It's non-portable code that's disallowed by the C++ standard.
New warning on __declspec attributes
In Visual Studio 2017 version 15.3, the compiler no longer ignores attributes if __declspec(...) is applied before
extern "C" linkage specification. Previously, the compiler would ignore the attribute, which could have runtime
implications. When the /Wall and /WX options are set, the following code produces warning C4768:
__declspec attributes before linkage specification are ignored :
This warning is off by default in 15.3, but on by default in 15.5, and only impacts code compiled with /Wall /WX .
decltype and calls to deleted destructors
In previous versions of Visual Studio, the compiler didn't detect when a call to a deleted destructor occurred in the
context of the expression associated with decltype . In Visual Studio 2017 version 15.3, the following code
produces error C2280: 'A<T>::~A(void)': attempting to reference a deleted function :
template<typename T>
struct A
{
~A() = delete;
};
template<typename T>
auto f() -> A<T>;
template<typename T>
auto g(T) -> decltype((f<T>()));
void h()
{
g(42);
}
struct A {};
template <typename> struct B {};
enum C { c1, c2, c3 };
int; // warning C4091 : '' : ignored on left of 'int' when no variable is declared
A; // warning C4091 : '' : ignored on left of 'main::A' when no variable is declared
B<int>; // warning C4091 : '' : ignored on left of 'B<int>' when no variable is declared
C; // warning C4091 : '' : ignored on left of 'C' when no variable is declared
To remove the warnings, comment-out or remove the empty declarations. In cases where the unnamed object is
intended to have a side effect (such as RAII), it should be given a name.
The warning is excluded under /Wv:18 and is on by default under warning level W2.
std::is_convertible for array types
Previous versions of the compiler gave incorrect results for std::is_convertible for array types. This required
library writers to special-case the Microsoft C++ compiler when using the std::is_convertible<...> type trait. In
the following example, the static asserts pass in earlier versions of Visual Studio but fail in Visual Studio 2017
version 15.3:
#include <type_traits>
static_assert(std::is_convertible<Array, Array>::value);
static_assert(std::is_convertible<const Array, const Array>::value, "");
static_assert(std::is_convertible<Array&, Array>::value, "");
static_assert(std::is_convertible<Array, Array&>::value, "");
std::is_convertible<From, To> is calculated by checking to see if an imaginary function definition is well formed:
Previous versions of the compiler ignored whether a destructor was private when deciding the result of
std::is_constructible. It now considers them. In the following example, the static asserts pass in earlier versions of
Visual Studio but fail in Visual Studio 2017 version 15.3:
#include <type_traits>
class PrivateDtor {
PrivateDtor(int) { }
private:
~PrivateDtor() { }
};
T obj(std::declval<Args>()...)
template<class T>
void f();
}
template<class T>
void f(T&, T&);
struct S {};
void f()
{
using N::f;
S s1, s2;
f(s1, s2); // C2668
}
To fix the code, remove the using N::f statement if you intended to call ::f() .
C2660: local function declarations and argument-dependent lookup
Local function declarations hide the function declaration in the enclosing scope and disable argument-dependent
lookup. However, previous versions of the compiler always did argument-dependent lookup in this case. It could
potentially lead to the wrong overload being chosen, and unexpected runtime behavior. Typically, the error is
because of an incorrect signature of the local function declaration. In the following example, Visual Studio 2017
version 15.3 correctly raises C2660 'f': function does not take two arguments :
struct S {};
void f(S, int);
void g()
{
void f(S); // C2660 'f': function does not take 2 arguments:
// or void f(S, int);
S s;
f(s, 0);
}
To fix the problem, either change the f(S) signature or remove it.
C5038: order of initialization in initializer lists
Class members get initialized in the order they're declared, not the order they appear in initializer lists. Previous
versions of the compiler didn't warn when the order of the initializer list differed from the order of declaration.
This issue could lead to undefined runtime behavior if one member's initialization depended on another member
in the list already being initialized. In the following example, Visual Studio 2017 version 15.3 (with /Wall ) raises
warning C5038: data member 'A::y' will be initialized after data member 'A::x' :
struct A
{
A(int a) : y(a), x(y) {} // Initialized in reverse, y reused
int x;
int y;
};
To fix the problem, arrange the initializer list to have the same order as the declarations. A similar warning is
raised when one or both initializers refer to base class members.
This warning is off-by-default, and only affects code compiled with /Wall .
template<typename... T>
int f(T* ...)
{
return 1;
}
template<typename T>
int f(const T&)
{
return 2;
}
int main()
{
int i = 0;
f(&i); // C2668
}
t161.cpp
t161.cpp(16): error C2668: 'f': ambiguous call to overloaded function
t161.cpp(8): note: could be 'int f<int*>(const T &)'
with
[
T=int*
]
t161.cpp(2): note: or 'int f<int>(int*)'
t161.cpp(16): note: while trying to match the argument list '(int*)'
The problem in the example above is that there are two differences in the types (const vs. non-const and pack vs.
non-pack). To eliminate the compiler error, remove one of the differences. Then the compiler can unambiguously
order the functions.
template<typename... T>
int f(T* ...)
{
return 1;
}
template<typename T>
int f(T&)
{
return 2;
}
int main()
{
int i = 0;
f(&i);
}
Exception handlers
Handlers of reference to array or function type are never a match for any exception object. The compiler now
correctly honors this rule and raises a level 4 warning. It also no longer matches a handler of char* or wchar_t*
to a string literal when /Zc:strictStrings is used.
int main()
{
try {
throw "";
}
catch (int (&)[1]) {} // C4843 (This should always be dead code.)
catch (void (&)()) {} // C4843 (This should always be dead code.)
catch (char*) {} // This should not be a match under /Zc:strictStrings
}
warning C4843: 'int (&)[1]': An exception handler of reference to array or function type is unreachable, use
'int*' instead
warning C4843: 'void (__cdecl &)(void)': An exception handler of reference to array or function type is
unreachable, use 'void (__cdecl*)(void)' instead
#include <functional>
#include <iostream>
using namespace std;
int main() {
std::tr1::function<int (int, int)> f = std::plus<int>(); //C4996
cout << f(3, 5) << std::endl;
f = std::multiplies<int>();
cout << f(3, 5) << std::endl;
}
warning C4996: 'std::tr1': warning STL4002: The non-standard std::tr1 namespace and TR1-only machinery are
deprecated and will be REMOVED. You can define _SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING to acknowledge that
you have received this warning.
#include <functional>
#include <iostream>
using namespace std;
int main() {
std::function<int (int, int)> f = std::plus<int>();
cout << f(3, 5) << std::endl;
f = std::multiplies<int>();
cout << f(3, 5) << std::endl;
}
#include <iterator>
#include <type_traits>
To fix the error, follow the instructions in the warning text, as demonstrated in the following code:
#include <iterator>
class MyIter {
public:
typedef std::random_access_iterator_tag iterator_category;
typedef int value_type;
typedef ptrdiff_t difference_type;
typedef int* pointer;
typedef int& reference;
#include <type_traits>
void f() {
char s[2] = {0}; // C4189. Either use the variable or remove it.
}
/* C only */
#pragma warning(disable:4001) //C4619
#pragma warning(disable:4179)
// single line comment
//* single line comment */
When the code doesn't need to be backwards compatible, you can avoid the warning by removing the
C4001/C4179 suppression. If the code does need to be backward compatible, then suppress C4619 only.
/* C only */
#pragma warning(disable:4619)
#pragma warning(disable:4001)
#pragma warning(disable:4179)
To fix the error, place the linkage specification before the __declspec attribute:
This new warning C4768 is given on some Windows SDK headers that were shipped with Visual Studio 2017
15.3 or older (for example: version 10.0.15063.0, also known as RS2 SDK). However, later versions of Windows
SDK headers (specifically, ShlObj.h and ShlObj_core.h) have been fixed so that they don't produce the warning.
When you see this warning coming from Windows SDK headers, you can take these actions:
1. Switch to the latest Windows SDK that came with Visual Studio 2017 version 15.5 release.
2. Turn off the warning around the #include of the Windows SDK header statement:
If a header file contains a variable declared extern constexpr , it needs to be marked __declspec(selectany) to
have its duplicate declarations combined correctly:
#include <typeinfo>
struct S;
#include <type_traits>
To avoid the error, when using is_convertible you should compare pointer types because a non-pointer-type
comparison might fail if one type is abstract:
#include <type_traits>
In C++17, throw() is an alias for noexcept , throw(<type list>) and throw(...) are removed, and certain types
may include noexcept . This change can cause source compatibility issues with code that conforms to C++14 or
earlier. The /Zc:noexceptTypes- switch can be used to revert to the C++14 version of noexcept while using
C++17 mode in general. It enables you to update your source code to conform to C++17 without having to
rewrite all your throw() code at the same time.
The compiler also now diagnoses more mismatched exception specifications in declarations in C++17 mode or
with /permissive- with the new warning C5043.
The following code generates C5043 and C5040 in Visual Studio 2017 version 15.5 when the /std:c++17 switch
is applied:
struct A {
virtual void f() throw();
};
struct B : A {
virtual void f() { } // error C2694
};
To remove the errors while still using /std:c++17 , either add the /Zc:noexceptTypes- switch to the command
line, or else update your code to use noexcept , as shown in the following example:
struct A {
virtual void f() noexcept;
};
struct B : A {
virtual void f() noexcept { }
};
Inline variables
Static constexpr data members are now implicitly inline , which means that their declaration within a class is
now their definition. Using an out-of-line definition for a static constexpr data member is redundant, and now
deprecated. In Visual Studio 2017 version 15.5, when the /std:c++17 switch is applied the following code now
produces warning C5041
'size': out-of-line definition for constexpr static data member is not needed and is deprecated in C++17 :
struct X {
static constexpr int size = 3;
};
const int X::size; // C5041
The compiler previously allowed defaulted functions to be declared with __declspec(nothrow) when the
corresponding base/member functions permitted exceptions. This behavior is contrary to the C++ standard and
can cause undefined behavior at runtime. The standard requires such functions to be defined as deleted if there's
an exception specification mismatch. Under /std:c++17 , the following code raises C2280
attempting to reference a deleted function. Function was implicitly deleted because the explicit exception
specification is incompatible with that of the implicit declaration.
struct A {
A& operator=(const A& other) { // No exception specification; this function may throw.
...
}
};
struct B : public A {
__declspec(nothrow) B& operator=(const B& other) = default;
};
int main()
{
B b1, b2;
b2 = b1; // error C2280
}
To correct this code, either remove __declspec(nothrow) from the defaulted function, or remove = default and
provide a definition for the function along with any required exception handling:
struct A {
A& operator=(const A& other) {
// ...
}
};
struct B : public A {
B& operator=(const B& other) = default;
};
int main()
{
B b1, b2;
b2 = b1;
}
template <>
struct A<void(*)()>
{
static const bool value = true;
};
int main()
{
return g(&f) ? 0 : 1; // C2027
}
The following code succeeds under /std:c++17 because the compiler chooses the new partial specialization
A<void (*)() noexcept> :
template <>
struct A<void(*)()>
{
static const bool value = true;
};
template <>
struct A<void(*)() noexcept>
{
static const bool value = true;
};
int main()
{
return g(&f) ? 0 : 1; // OK
}
template<typename T>
void S<T>::f(int = 0) {} // Re-definition necessary
In /std:c++17 mode in Visual Studio 2017 version 15.7, the default argument isn't ignored:
template<typename T>
struct S {
void f(int = 0);
};
template<typename T>
void S<T>::f(int) {} // Default argument is used
template<typename T>
struct B {
using type = T;
};
template<typename T>
struct D : B<T*> {
using type = B<T*>::type;
};
Visual Studio 2017 version 15.7, in /std:c++17 mode, requires the typename keyword in the using statement in
D. Without typename , the compiler raises warning C4346: 'B<T*>::type': dependent name is not a type and error
C2061: syntax error: identifier 'type' :
template<typename T>
struct B {
using type = T;
};
template<typename T>
struct D : B<T*> {
using type = typename B<T*>::type;
};
int main() {
f(); // warning: discarding return value
// of function with 'nodiscard'
}
template<typename T>
struct B {};
template<typename T>
struct D : B<T>
{
template<typename ...C>
D() : B() {} // C2614. Missing template arguments to B.
};
D<int> d;
#include <array>
struct X {
unsigned short a;
unsigned char b;
};
int main() {
constexpr std::array<X, 2> xs = {
{ 1, 2 },
{ 3, 4 }
};
return 0;
}
In Visual Studio 2017 version 15.7 update 3 and later, the previous example now raises C2078
too many initializers . The following example shows how to fix the code. When initializing a std::array with
nested brace-init-lists, give the inner array a braced-list of its own:
#include <array>
struct X {
unsigned short a;
unsigned char b;
};
int main() {
constexpr std::array<X, 2> xs = {{ // note double braces
{ 1, 2 },
{ 3, 4 }
}}; // note double braces
return 0;
}
To fix the error, change to code to the following (with the attribute placed before the '=' of the alias definition):
The C++ standard doesn't allow a user to add forward declarations or definitions into namespace std . Adding
declarations or definitions to namespace std or to a namespace within namespace std now results in
undefined behavior.
At some time in the future, Microsoft will move the location where some standard library types are defined. This
change will break existing code that adds forward declarations to namespace std . A new warning, C4643, helps
identify such source issues. The warning is enabled in /default mode and is off by default. It will impact
programs that are compiled with /Wall or /WX .
The following code now raises C4643:
Forward declaring 'vector' in namespace std is not permitted by the C++ Standard .
namespace std {
template<typename T> class vector;
}
To fix the error, use an include directive rather than a forward declaration:
#include <vector>
Without this error, the following program will compile but will generate an infinite loop:
class X {
public:
X(int, int);
X(int v) : X(v){}
};
class X {
public:
X(int, int);
X(int v) : X(v, 0) {}
};
struct Data {
int x;
};
int main()
{
switch (0) {
case MY_OFFSET(Data, x): return 0;
default: return 1;
}
}
struct Data {
int x;
};
int main()
{
switch (0) {
case offsetof(Data, x): return 0;
default: return 1;
}
}
template<typename... T>
class X : public T... { };
class S { };
int main()
{
X<const S> x;
}
template<typename T>
struct X : Base<T>
{
void example()
{
Base<T>::example<int>();
}
};
To fix the error, add the template keyword to the Base<T>::example<int>(); statement, as shown in the following
example:
template<typename T> struct Base
{
template<class U> void example() {}
};
template<typename T>
struct X : Base<T>
{
void example()
{
// Add template keyword here:
Base<T>::template example<int>();
}
};
private:
template <template <typename...> typename Type, typename... Args>
static constexpr A<Args...> from_template(A<Type<Args...>>);
};
A<>::from_template_t<A<int>> a;
In Visual Studio 2017 version 15.9, in /permissive- mode, the compiler raises C3861:
'from_template': identifier not found .
To fix the error, declare from_template before from_template_t .
Modules changes
In Visual Studio 2017, version 15.9, the compiler raises C5050 whenever the command-line options for modules
aren't consistent between the module creation and module consumption sides. In the following example, there
are two issues:
On the consumption side (main.cpp), the option /EHsc isn't specified.
The C++ version is /std:c++17 on the creation side, and /std:c++14 on the consumption side.
#include <utility>
using size_t = std::size_t;
struct Alloc
{
static constexpr size_t size = 10;
};
int main()
{
A<void> a;
AlignedStorage<Alloc::size> buf;
if (f<Alloc>(a, buf) != 2)
{
return 1;
}
return 0;
}
The implementation divergence is because of a regression in the C++ standard wording. The resolution to core
issue 2235 removed some text that would allow these overloads to be ordered. The current C++ standard doesn't
provide a mechanism to partially order these functions, so they're considered ambiguous.
As a workaround, we recommended that you not rely on partial ordering to resolve this problem. Instead, use
SFINAE to remove particular overloads. In the following example, we use a helper class IsA to remove the first
overload when Alloc is a specialization of A :
#include <utility>
using size_t = std::size_t;
struct Alloc
{
static constexpr size_t size = 10;
};
int main()
{
A<void> a;
AlignedStorage<Alloc::size> buf;
if (f<Alloc>(a, buf) != 2)
{
return 1;
}
return 0;
}
template<typename T>
struct S
{
constexpr void f();
};
template<>
constexpr void S<int>::f()
{
g(); // C3615 in 15.9
}
In Visual Studio 2017 version 15.9, the code raises this error:
To avoid the error, remove the constexpr qualifier from the explicit instantiation of the function f() .
See also
Microsoft C++ language conformance table
Microsoft C++ language conformance table
12/18/2020 • 24 minutes to read • Edit Online
Standards conformance for the Microsoft C++ compiler in Visual Studio (MSVC) is a work in progress. Here's a
summary of our ISO Standard C++ language and library conformance by Visual Studio version. Each compiler
and standard library feature name links to the ISO Standard C++ proposal paper that describes the feature, if one
is available at publication time. The Suppor ted column lists the Visual Studio version in which support for the
feature first appeared.
For details on Visual Studio 2017 or Visual Studio 2019 MSVC conformance improvements, see C++
conformance improvements in Visual Studio. For a list of other changes, see What's New for Visual C++ in Visual
Studio. For conformance changes in earlier versions, see Visual C++ change history and Visual C++ What's New
2003 through 2015. For current news from the C++ team, visit the C++ team blog.
NOTE
There are no binary breaking changes between Visual Studio 2015, Visual Studio 2017, and Visual Studio 2019. For more
information, see C++ binary compatibility between Visual Studio 2015, 2017, and 2019
Compiler features
F EAT URE SUP P O RT ED
VS 2017 15.3 17
P0028R4 Using attribute namespaces without
repetition
VS 2017 15.3 17
P0138R2 Direct-list-init of fixed enums from
integers
VS 2017 15.5 17
P0522R0 Matching template template-parameters to
compatible arguments
VS 2017 15.7 17
P0091R3 Template argument deduction for class
templates
P0512R0 Class template argument deduction issues
VS 2017 15.7 17
P0127R2 Declaring non-type template parameters with
auto
VS 2017 15.7 17
P0702R1 Fixing class template argument deduction for
initializer-list ctors
VS 2019 16.0 17
P0961R1 Relaxing the structured bindings
customization point finding rules
VS 2019 16.0 17
P0969R0 Allowing structured bindings to accessible
members
VS 2019 16.4 17
P1825R0 Merged wording for P0527R1 and P1155R3, more
implicit moves
VS 2019 16.5 17
P0962R2 Relaxing the range-for loop customization
point finding rules
No
P0859R0 CWG 1581: When are constexpr member
functions defined
VS 2015 14
P0704R1 Fixing const lvalue ref-qualified pointers
to members
VS 2015 14
P1041R4 Make char16_t/char32_t string literals be
UTF-16/32
VS 2017 15.0 14
P1330R0 Changing the active member of a union inside
constexpr
F EAT URE SUP P O RT ED
VS 2019 16.0 20
P0515R3 Three-way (spaceship) comparison operator
<=>
VS 2019 16.0 20
P1008R1 Prohibiting aggregates with user-declared
constructors
VS 2019 16.1 20
P0846R0 ADL and function templates that are not
visible
VS 2019 16.2 20
P0428R2 Familiar template syntax for generic lambdas
VS 2019 16.2 20
P0624R2 Default constructible and assignable
stateless lambdas
VS 2019 16.2 20
P0780R2 Allowing pack expansion in lambda init-
capture
VS 2019 16.2 20
P1120R0 Consistency improvements for <=> and other
comparison operators
VS 2019 16.3 20
P1084R2 Today's return-type-requirements are
insufficient
VS 2019 16.4 20
P1091R3 Extending structured bindings to be more
like variable declarations
F EAT URE SUP P O RT ED
VS 2019 16.5 20
P0306R4 Adding __VA_OPT__ for comma omission and
comma deletion
VS 2019 16.5 20
P1161R3 Deprecate uses of the comma operator in
subscripting expressions
VS 2019 16.5 20
P1703R1 Recognizing header unit imports requires
full preprocessing
VS 2019 16.6 20
P1907R1 Inconsistencies with non-type template
parameters
VS 2019 16.6 20
P1971R0 US053: Mandate the return type for
return_void and return_value to be void
VS 2019 16.6 20
P1971R0 US065: Apply Coroutines issue 24 from
P0664R8
VS 2019 16.7 20
P0388R4 Permit conversions to arrays of unknown
bound
VS 2019 16.7 20
P0466R5 Layout-compatibility and Pointer-
interconvertibility Traits
VS 2019 16.7 20
P0722R3 Efficient sized delete for variable sized
classes
VS 2019 16.7 20
P1331R2 Permitting trivial default initialization in
constexpr contexts
VS 2019 16.7 20
P1358R0 2310: Type completeness and derived-to-base
pointer conversions
VS 2019 16.7 20
P1452R2 On the non-uniform semantics of return-type-
requirements
VS 2019 16.7 20
P1616R1 Using unconstrained TTPs with constrained
templates
VS 2019 16.7 DR
P1957R1 Converting from T* to bool should be
considered narrowing (re: US 212)
VS 2019 16.7 20
P1968R0 CWG 2282: Consistency with mismatched
aligned/non-over-aligned allocation/deallocation
functions
VS 2019 16.7 20
P1969R0 CWG 2280: Matching a usual deallocation
function with placement new
VS 2019 16.7 20
P1969R0 CWG 2382: Array allocation overhead for non-
allocating placement new
VS 2019 16.7 20
P1971R0 US052: Non-executed return statements in
coroutines
VS 2019 16.7 20
P1972R0 US105: Check satisfaction of constraints for
non-templates when forming pointer to function
VS 2019 16.7 20
P1980R0 CA096: Declaration matching for non-
dependent requires-clauses
VS 2019 16.7 20
P2103R0 US033: Allow "import" inside linkage-
specifications
VS 2019 16.7 20
P2107R0 US064: Copy semantics of coroutine
parameters
VS 2019 16.8 20
P0848R3 Conditionally trivial special member
functions
VS 2019 16.8 20
P0960R3 Allow initializing aggregates from a
parenthesized list of values
VS 2019 16.8 20
P1811R0 Relaxing redefinition restrictions for re-
exportation robustness
VS 2019 16.8 20
P1874R1 Dynamic Initialization Order of Non-Local
Variables in Modules
VS 2019 16.8 20
P1975R0 Fixing the wording of parenthesized
aggregate-initialization
Partial
P0641R2 const mismatch with defaulted copy
constructor
F EAT URE SUP P O RT ED
Partial
P1141R2 Yet another approach for constrained
declarations
No
P1064R0 Allowing virtual function calls in constant
expressions
P1143R2 constinit No
No
P1327R1 Allowing dynamic_cast, polymorphic typeid in
constant expressions
No
P1668R1 Permitting unevaluated inline assembly in
constexpr functions
N/A
P0735R1 Interaction of memory_order_consume with
release sequences
VS 2019 16.1 20
P0457R2 starts_with()/ends_with() For
basic_string/basic_string_view
VS 2019 16.1 20
P0458R2 contains() For Ordered And Unordered
Associative Containers
VS 2019 16.1 20
P0646R1 list/forward_list
remove()/remove_if()/unique() Return size_type
VS 2019 16.2 20
P0020R6 atomic<float>, atomic<double>, atomic<long
double>
VS 2019 16.2 20
P0482R6 char8_t: A type for UTF-8 characters and
strings
VS 2019 16.2 20
P0771R1 noexcept For std::function's Move
Constructor
VS 2019 16.3 20
P0919R3 Heterogeneous Lookup For Unordered
Containers
F EAT URE SUP P O RT ED
VS 2019 16.5 20
P1651R0 bind_front() Should Not
Unwrap reference_wrapper
VS 2019 16.5 20
P1690R1 Refining Heterogeneous Lookup For Unordered
Containers
VS 2019 16.6 20
P0357R3 Supporting Incomplete Types In
reference_wrapper
VS 2019 16.6 14
P0935R0 Eradicating Unnecessarily Explicit Default
Constructors
VS 2019 16.6 20
P1006R1 constexpr For
pointer_traits<T*>::pointer_to()
VS 2019 16.6 14
P1165R1 Consistently Propagating Stateful Allocators
In basic_string's operator+()
VS 2019 16.7 20
P0528R3 Atomic Compare-And-Exchange With Padding
Bits
VS 2019 16.7 20
P1831R1 Deprecating volatile in the standard library
VS 2019 16.7 20
P1871R1 Concept traits should be named after
concepts
VS 2019 16.7 20
P1956R1 <bit> has_single_bit(), bit_ceil(),
bit_floor(), bit_width()
VS 2019 16.7 20
P1976R2 Fixed-size span construction from dynamic
range
VS 2019 16.7 20
P2102R0 Make "implicit expression variations" more
explicit
VS 2019 16.7 20
P2116R0 Remove tuple-like protocol support from
fixed-extent span
VS 2019 16.8 20
P0528R3 Library support for atomic compare-and-
exchange with padding bits
VS 2019 16.8 20
P1123R0 Editorial Guidance for merging P0019r8 and
P0528r3
P0053R7 <syncstream> No
P0753R2 osyncstream Manipulators
F EAT URE SUP P O RT ED
P0339R6 polymorphic_allocator<> No
No
P0408R7 Efficient access To basic_stringbuf's buffer
No
P0466R5 Library support for layout-compatibility and
pointer-interconvertibility traits
No
P0475R1 Guaranteed Copy Elision For Piecewise
Construction
No
P0591R4 Utility Functions For Uses-Allocator
Construction
No
P0608R3 Improving variant's Converting
Constructor/Assignment
P1007R3 assume_aligned() No
No
P1020R1 Smart Pointer Creation With Default
Initialization
P1208R6 <source_location> No
No
P1285R0 Improving Completeness Requirements For Type
Traits
F EAT URE SUP P O RT ED
No
P1771R1 Library support for [[nodiscard]] for
constructors
VS 2015 rem
N4190 Removing auto_ptr, random_shuffle(), And Old
<functional> Stuff
VS 2015 14
N4279 insert_or_assign()/try_emplace() For
map/unordered_map
VS 2013 14
N4510 Supporting Incomplete Types In
vector/list/forward_list
VS 2015.2 14
P0006R0 Variable Templates For Type Traits
(is_same_v, etc.)
VS 2015.2 14
P0013R1 Logical Operator Type Traits (conjunction,
etc.)
VS 2017 15.3 17
P0031R0 constexpr For <array> (Again) And <iterator>
VS 2017 15.0
P0032R3 Homogeneous Interface For
variant/any/optional
VS 2017 15.3 17
P0154R1 hardware_destructive_interference_size, etc.
VS 2017 15.3 14
P0418R2 atomic compare_exchange memory_order
Requirements
VS 2017 15.7
P0433R2 Integrating template deduction for class
templates into the standard library
VS 2017 15.0
P0504R0 Revisiting
in_place_t/in_place_type_t<T>/in_place_index_t<I>
VS 2017 15.0
P0510R0 Rejecting variants Of Nothing, Arrays,
References, And Incomplete Types
VS 2017 15.3 14
P0558R1 Resolving atomic<T> Named Base Class
Inconsistencies
VS 2017 15.317
P0602R4 Propagating Copy/Move Triviality In
variant/optional
VS 2017 15.3 17
P0604R0 Changing is_callable/result_of To
invoke_result, is_invocable, is_nothrow_invocable
VS 2015
N3471 constexpr For <initializer_list>, <tuple>,
<utility>
VS 2015
N3642 UDLs For <chrono>, <string> (1729ms, "meow"s,
etc.)
VS 2015
N3669 Fixing constexpr Member Functions Without
const
VS 2015
N3671 Dual-Range equal(), is_permutation(),
mismatch()
VS 2015
N3891 Renaming shared_mutex (Timed) To
shared_timed_mutex
VS 2013
N3655 Alias Templates For <type_traits> (decay_t,
etc.)
A group of papers listed together indicates a Standard feature along with one or more approved improvements or
expansions. These features are implemented together.
Supported values
No means not yet implemented.
Par tial means the implementation is incomplete. For more information, see the Notes section.
VS 2010 indicates features that are supported in Visual Studio 2010.
VS 2013 indicates features that are supported in Visual Studio 2013.
VS 2015 indicates features that are supported in Visual Studio 2015 (RTW).
VS 2015.2 and VS 2015.3 indicate features that are supported in Visual Studio 2015 Update 2 and Visual
Studio 2015 Update 3, respectively.
VS 2017 15.0 indicates features that are supported in Visual Studio 2017 version 15.0 (RTW).
VS 2017 15.3 indicates features that are supported in Visual Studio 2017 version 15.3.
VS 2017 15.5 indicates features that are supported in Visual Studio 2017 version 15.5.
VS 2017 15.7 indicates features that are supported in Visual Studio 2017 version 15.7.
VS 2019 16.0 indicates features that are supported in Visual Studio 2019 version 16.0 (RTW).
VS 2019 16.1 indicates features that are supported in Visual Studio 2019 version 16.1.
VS 2019 16.2 indicates features that are supported in Visual Studio 2019 version 16.2.
VS 2019 16.3 indicates features that are supported in Visual Studio 2019 version 16.3.
VS 2019 16.4 indicates features that are supported in Visual Studio 2019 version 16.4.
VS 2019 16.5 indicates features that are supported in Visual Studio 2019 version 16.5.
VS 2019 16.6 indicates features that are supported in Visual Studio 2019 version 16.6.
VS 2019 16.7 indicates features that are supported in Visual Studio 2019 version 16.7.
VS 2019 16.8 indicates features that are supported in Visual Studio 2019 version 16.8.
Notes
A In /std:c++14 mode, dynamic exception specifications remain unimplemented, and throw() is still treated as a
synonym for __declspec(nothrow) . In C++17, dynamic exception specifications were mostly removed by
P0003R5, leaving one vestige: throw() is deprecated and required to behave as a synonym for noexcept . In
/std:c++17 mode, MSVC now conforms to the Standard by giving throw() the same behavior as noexcept , that
is, enforcement via termination.
The compiler option /Zc:noexceptTypes requests our old behavior of __declspec(nothrow) . It's likely that throw()
will be removed in C++20. To help with migrating code in response to these changes in the Standard and our
implementation, new compiler warnings for exception specification issues have been added under /std:c++17
and /permissive- .
B Supported in /permissive- mode in Visual Studio 2017 version 15.7. For more information, see Two-phase
name lookup support comes to MSVC.
C Starting in Visual Studio 2017 version 15.8, the compiler provides support for the C99 preprocessor via the
/experimental:preprocessor compiler switch. Starting in Visual Studio 2019 version 16.6, the compiler fully
implements the C99 preprocessor via the /Zc:preprocessor switch. It is on by default when the compiler switch
/std:c11 or /std:c17 is specified.
charconv from_chars() and to_chars() are available for integers. The timeline for floating-point from_chars()
and floating-point to_chars() is as follows:
VS 2017 15.7: Integer from_chars() and to_chars() .
VS 2017 15.8: Floating-point from_chars() .
VS 2017 15.9: Floating-point to_chars() overloads for shortest decimal.
VS 2019 16.0: Floating-point to_chars() overloads for shortest hex and precision hex.
VS 2019 16.2: Floating-point to_chars() overloads for precision fixed and precision scientific.
VS 2019 16.4: The floating-point to_chars() overload for precision general.
parallel C++17's parallel algorithms library is complete. Complete doesn't mean every algorithm is parallelized
in every case. The most important algorithms have been parallelized, and execution policy signatures are
provided even where algorithms aren't parallelized. Our implementation's central internal header, yvals_core.h,
contains the following "Parallel Algorithms Notes": C++ allows an implementation to implement parallel
algorithms as calls to the serial algorithms. This implementation parallelizes several common algorithm calls, but
not all.
The following algorithms are parallelized:
adjacent_difference , adjacent_find , all_of , any_of , count ,
, equal , exclusive_scan , find ,
count_if
find_end , find_first_of , find_if , find_if_not , for_each , for_each_n , inclusive_scan , is_heap ,
is_heap_until , is_partitioned , is_sorted , is_sorted_until , mismatch , none_of , partition , reduce ,
remove , remove_if , replace , replace_if , search , search_n , set_difference , set_intersection , sort ,
stable_sort , transform , transform_exclusive_scan , transform_inclusive_scan , transform_reduce
See also
C++ Language Reference
C++ Standard Library
C++ conformance improvements in Visual Studio
What's New for Visual C++ in Visual Studio
Visual C++ change history 2003 through 2015
Visual C++ What's New 2003 through 2015
C++ team blog
Supported Platforms (Visual C++)
12/18/2020 • 2 minutes to read • Edit Online
Apps built by using Visual Studio can be targeted to various platforms, as follows.
Windows XP X* X*
Windows Vista X X
Windows 7 X X
Windows 8 X X X
Windows 8.1 X X X
Windows 10 X X X X
Android ** X X X X
iOS ** X X X X
Linux *** X X X X
* You can use the Windows XP platform toolset included in Visual Studio 2017, Visual Studio 2015, Visual Studio
2013, and Visual Studio 2012 Update 1 to build Windows XP and Windows Server 2003 projects. For information
on how to use this platform toolset, see Configuring Programs for Windows XP. For additional information on
changing the platform toolset, see How to: Modify the Target Framework and Platform Toolset.
** You can install the Mobile development with C++ workload in the installer for Visual Studio 2017 and later.
In Visual Studio 2015 setup, choose the optional Visual C++ for Cross Platform Mobile Development
component to target iOS or Android platforms. For instructions, see Install Visual C++ for Cross-Platform Mobile
Development. To build iOS code, you must have a Mac computer and meet other requirements. For a list of
prerequisites and installation instructions, see Install And Configure Tools to Build using iOS. You can build x86 or
ARM code to match the target hardware. Use x86 configurations to build for the iOS simulator, Microsoft Visual
Studio Emulator for Android, and some Android devices. Use ARM configurations to build for iOS devices and most
Android devices.
*** You can install the Linux development with C++ workload in the installer for Visual Studio 2017 and later to
target Linux platforms. For instructions, see Download, Install and Setup the Linux Workload. This toolset compiles
your executable on the target machine, so you can build for any supported architecture.
**** ARM64 support is available in Visual Studio 2017 and later.
For information about how to set the target platform configuration, see How to: Configure Visual C++ Projects to
Target 64-Bit, x64 Platforms.
See also
Visual C++ Tools and Features in Visual Studio Editions
Getting Started
C++ Tools and Features in Visual Studio Editions
12/18/2020 • 9 minutes to read • Edit Online
The following C++ features are available in Visual Studio 2019. Unless stated otherwise, all features are available
in all editions: Visual Studio Community, Visual Studio Professional, and Visual Studio Enterprise. Some features
require specific workloads or optional components, which you can install with the Visual Studio Installer.
Platforms
Windows Desktop
Universal Windows Platform ((tablet, PC, Xbox, IoT, and HoloLens))
Linux
Android
iOS
Compilers
MSVC 32-bit compiler for x86, x64, ARM, and ARM64
MSVC 64-bit compiler for x86, x64, ARM, and ARM64
GCC cross-compiler for ARM
Clang/LLVM
On Windows, Clang/LLVM 7.0, targeting x86 or x64 (CMake support only). Other Clang versions might
work but are not officially supported.
On Linux, any Clang/LLVM installation supported by the distro.
C++ Workloads
Visual Studio includes the following workloads for C++ development. You can install any or all of these, along with
other workloads such as .NET Desktop Development, Python Development, Azure Development, Visual Studio
Extension Development, and others.
Desktop development with C++
Included:
C++ core desktop features
Optional Components:
MSVC v142 - VS 2019 C++ x64/x86 build tools (v14.21)
Windows 10 SDK (10.0.17763.0)
Just-In-Time debugger
C++ profiling tools
C++ CMake tools for Windows
C++ ATL for v142 build tools (x86 & x64)
Test Adapter for Boost.Test
Test Adapter for Google Test
Live Share
IntelliCode
IntelliTrace (Enterprise only)
C++ MFC for v142 build tools (x86 & x64)
C++/CLI support for v142 build tools (14.21)
C++ Modules for v142 build tools (x64/x86 – experimental)
Clang compiler for Windows
IncrediBuild - Build Acceleration
Windows 10 SDK (10.0.17134.0)
Windows 10 SDK (10.0.16299.0)
MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)
MSVC v140 - VS 2015 C++ build tools (v14.00)
Linux development with C++
Included:
C++ core features
Windows Universal C Runtime
C++ for Linux Development
Optional Components:
C++ CMake tools for Linux
Embedded and IoT development tools
Universal Windows Platform development
Included:
Blend for Visual Studio
.NET Native and .NET Standard
NuGet package manager
Universal Windows Platform tools
Windows 10 SDK (10.0.17763.0)
Optional Components:
IntelliCode
IntelliTrace (Enterprise only)
USB Device Connectivity
C++ (v142) Universal Windows Platform tools
C++ (v141) Universal Windows Platform tools
Graphics debugger and GPU profiler for DirectX
Windows 10 SDK (10.0.18362.0)
Windows 10 SDK (10.0.17134.0)
Windows 10 SDK (10.0.16299.0)
Architecture and analysis tools
C++ Game Development
Included:
C++ core features
Windows Universal C Runtime
C++ 2019 Redistributable Update
MSVC v142 - VS 2019 C++ x64/x86 build tools (v14.21)
Optional Components:
C++ profiling tools
Windows 10 SDK (10.0.17763.0)
IntelliCode
IntelliTrace (Enterprise only)
Windows 10 SDK (10.0.17134.0)
Windows 10 SDK (10.0.16299.0)
IncrediBuild - Build Acceleration
Cocos
Unreal Engine installer
Android IDE support for Unreal engine
Mobile development with C++
Included:
C++ core features
Android SDK setup (API level 25) (local install for Mobile development with C++)
Optional Components:
Android NDK (R16B)
Apache Ant (1.9.3)
C++ Android development tools
IntelliCode
Google Android Emulator (API Level 25) (local install)
Intel Hardware Accelerated Execution Manager (HAXM) (local install)
Android NDK (R16B) (32bit)
C++ iOS development tools
IncrediBuild - Build Acceleration
Individual components
You can install these components independently from any workload.
JavaScript diagnostics
Live Share
C++ Universal Windows Platform runtime for v142 build tools
ClickOnce Publishing
Microsoft Visual Studio Installer Projects
Project Templates
The following project templates are available depending on which workloads you have installed.
Windows Desktop:
Empty Project
Console App
Windows Desktop Wizard
Windows Desktop Application
Shared Items Project
MFC App
Dynamic Link Library
CLR Empty Project
CLR Console App
Static Library
CMake Project
ATL Project
MFC Dynamic Link Library
CLR Class Library
Makefile Project (Windows)
MFC ActiveXControl
Native Unit Test Project
Google Test
Universal Windows Platform (C++/CX):
Blank App
DirectX 11 and XAML App
DirectX 11 App
DirectX 12 App
Unit Test App
DLL
Windows Runtime Component
Static Library
Windows Application Packaging Project
Linux:
Console App (Linux)
Empty Project (Linux)
Raspberry Pi Blink
Makefile Project (Linux)
Tools
Incremental Linker (Link.exe)
Microsoft Makefile Utility (Nmake.exe)
Lib Generator (Lib.exe)
Windows Resource Compiler (Rc.exe)
Windows Resource to Object Converter (CvtRes.exe)
Browse Information Maintenance Utility (BscMake.exe)
C++ Name Undecorator (Undname.exe)
COFF/PE Dumper (Dumpbin.exe)
COFF/PE Editor (Editbin.exe)
MASM (Ml.exe)
Spy++
ErrLook
AtlTrace
Inference Rules
Profile Guided Optimizations
Debugging Features
Native Debugging
natvis (native type visualization)
Graphics Debugging
Managed Debugging
GPU usage
Memory usage
Remote Debugging
SQL Debugging
Static Code Analysis
Data Features
Data Designer
Data Objects
Web Services
Server Explorer
See also
Install Visual Studio
What's New in Visual Studio
C++ project types in Visual Studio
The following tables show Visual C++ features that are available in Visual Studio 2017. An X in a cell indicates that
the feature is available; an empty cell indicates that the feature is not available. Notes in parentheses indicate that a
feature is available, but restricted.
Platforms
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R C O M M UN IT Y / P RO F ES VISUA L ST UDIO
P L AT F O RM W IN DO W S 10 W IN DO W S DESK TO P SIO N A L EN T ERP RISE
Windows Desktop X X X
Universal Windows X X X
Platform ((phone,
tablet, PC, Xbox, IoT,
and HoloLens))
Linux X X
Android X X
iOS X X
Compilers
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R P RO F ESSIO N A L / VISUA L ST UDIO
C O M P IL ER W IN DO W S W IN DO W S DESK TO P C O M M UN IT Y EN T ERP RISE
X86_arm cross- X X X
compiler
ATL X X
MFC X X
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R P RO F ESSIO N A L / VISUA L ST UDIO
L IB RA RY O R H EA DER W IN DO W S W IN DO W S DESK TO P C O M M UN IT Y EN T ERP RISE
OpenMP 2.0 X X X X
Project Templates
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R P RO F ESSIO N A L / VISUA L ST UDIO
T EM P L AT E W IN DO W S W IN DO W S DESK TO P C O M M UN IT Y EN T ERP RISE
Direct3D App X X X
DLL (Universal X X X
Windows)
Static Library X X X
(Universal Windows)
Windows Runtime X X X
Component
ATL Project X X
CLR Console X X X
Application
Custom Wizard X X
Empty Project X X X
Makefile Project X X X
MFC Application X X
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R P RO F ESSIO N A L / VISUA L ST UDIO
T EM P L AT E W IN DO W S W IN DO W S DESK TO P C O M M UN IT Y EN T ERP RISE
MFC DLL X X
Test Project X X X X
Win32 Console X X X
Application
Win32 Project X X X
Tools
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R P RO F ESSIO N A L / VISUA L ST UDIO
TO O L W IN DO W S W IN DO W S DESK TO P C O M M UN IT Y EN T ERP RISE
Incremental Linker X X X X
(Link.exe)
Program X X X
Maintenance Utility
(Nmake.exe)
Lib Generator X X X X
(Lib.exe)
Windows Resource X X X X
Compiler (Rc.exe)
Windows Resource to X X X
Object Converter
(CvtRes.exe)
Browse Information X X X X
Maintenance Utility
(BscMake.exe)
C++ Name X X X X
Undecorator
(Undname.exe)
COFF/PE Dumper X X X X
(Dumpbin.exe)
COFF/PE Editor X X X X
(Editbin.exe)
MASM (Ml.exe) X X
Spy++ X X
ErrLook X X
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R P RO F ESSIO N A L / VISUA L ST UDIO
TO O L W IN DO W S W IN DO W S DESK TO P C O M M UN IT Y EN T ERP RISE
AtlTrace X X
Devenv.com X X
Inference Rules X X
Upgrade VCBuild X X X X
.vcproj projects to
MSBuild
(VCUpgrade.exe)
Profile Guided X X
Optimizations
Debugging Features
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R P RO F ESSIO N A L / VISUA L ST UDIO
DEB UGGIN G F EAT URE W IN DO W S W IN DO W S DESK TO P C O M M UN IT Y EN T ERP RISE
Native Debugging X X X X
Graphics Debugging X X X
Managed Debugging X X X
GPU usage X X X
Memory usage X X X
Remote Debugging X X X X
SQL Debugging X X
XAML Designer X X X
CSS Style X X X X
Designer/Editor
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R P RO F ESSIO N A L / VISUA L ST UDIO
DESIGN ER O R EDITO R W IN DO W S W IN DO W S DESK TO P C O M M UN IT Y EN T ERP RISE
HTML X X X X
Designer/Editor
XML Editor X X X X
Productivity Features: X X X X
Refactoring,
IntelliSense, C++
Code Formatting
Windows Forms X X X
Designer
Data Designer X X
Native Resource X X
Editor (.rc files)
Resource Editors X X X X
Model editor X X X
Shader designer X X X
Data Features
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R P RO F ESSIO N A L / VISUA L ST UDIO
DATA F EAT URE W IN DO W S W IN DO W S DESK TO P C O M M UN IT Y EN T ERP RISE
Data Designer X X
Data Objects X X
Web Services X X
Server Explorer X X
Native Multi- X X X
targeting
Managed Multi- X X X
targeting
Parallel Builds X X X X
Build Customizations X X X X
Property Pages X X X X
Extensibility
Extensibility Object X X
Models
Code Model X X
Project Model X X
Resource Editor X X
Model
Wizard Model X X
Debugger Object X X
Model
Unit Testing X X X
(managed framework)
Code coverage X
Manual testing X
VISUA L ST UDIO VISUA L ST UDIO VISUA L ST UDIO
EXP RESS F O R EXP RESS F O R P RO F ESSIO N A L / VISUA L ST UDIO
TO O L W IN DO W S W IN DO W S DESK TO P C O M M UN IT Y EN T ERP RISE
Exploratory testing X
Test case X
management
See also
Install Visual Studio
What's New in Visual Studio
C++ project types in Visual Studio
Install C11 and C17 support in Visual Studio
11/2/2020 • 4 minutes to read • Edit Online
Support for C11 and C17 standards requires Visual Studio 2019 version 16.8 or later. To see the documentation for
this version, set the Visual Studio Version selector control for this article to Visual Studio 2019. It's found at the top
of the table of contents on this page.
Support for C11 and C17 standards is available starting in Visual Studio 2019 version 16.8. Support requires an
updated Universal C Runtime (UCRT) and the latest Windows SDK updates, to work properly with the conforming
preprocessor ( /Zc:preprocessor ).
Windows SDK releases correspond with Windows OS releases. Since there hasn't been a Windows release with
these changes, you'll need an Insider Preview Windows SDK. That's a preview version of the Windows SDK that
corresponds with Windows builds currently being flighted, or tested, by Windows Insiders. After you install the
Insider Preview Windows 10 SDK, Visual Studio projects configured to use the latest Windows SDK will use the
Insider Preview.
Prerequisites
Visual Studio 2019 version 16.8 Preview 3 or later installed and running on your computer. In the install, include
the Desktop development with C++ workload. You can download the latest Preview from the Visual Studio
Preview page. If Visual Studio isn't installed yet, see Install C++ support in Visual Studio for installation
instructions.
Choose Install to install the selected SDK components. The SDK takes a couple of minutes to complete installation.
When it completes, open Visual Studio.
The C++ Language Standard is used when the language is C++. It's the default when the file extension is .cpp . The
C Language Standard version is used when the language is C. It's the default when the file extension is .c . To build
using C11 or C17, put your source code in a .c file, or set the code to compile as C. You can set this property for
your project on the Configuration Proper ties > C/C++ > Advanced page. Set the Compile As property to
Compile as C code (/TC) .
Congratulations, you've set up everything you need to build C11 and C17 code in Visual Studio 2019 version 16.8
preview 3!
See also
/std (Specify language standard version)
Visual Studio C++ Samples
11/2/2020 • 49 minutes to read • Edit Online
Samples for Visual Studio C++ are available on the web. Microsoft has produced many C++ samples that
demonstrate different functionalities across multiple technologies. Here are a few of the places to find additional
samples:
Microsoft Docs samples - C++
Windows samples on GitHub
Windows Dev Center code samples
CodePlex sample archive
ADO code samples
Windows Hardware development samples
IMPORTANT
This sample code is intended to illustrate a concept, and it shows only the code that is relevant to that concept. It may not
meet the security requirements for a specific environment, and it should not be used exactly as shown. We recommend that
you add security and error-handling code to make your projects more secure and robust. Microsoft provides this sample
code "AS IS" with no warranties.
ATL samples
ATL samples - Advanced
SA M P L E N A M E DESC RIP T IO N
ATLSecurity Shows how to use the ATL security classes to examine security
settings.
SA M P L E N A M E DESC RIP T IO N
Scribble (using MFC) An MFC implementation of the Scribble sample, updated and
extended to include new .NET functionality.
ComTypeLibfor7 samples
SA M P L E N A M E DESC RIP T IO N
Compiler samples
Compiler samples - General
SA M P L E N A M E DESC RIP T IO N
CRT samples
SA M P L E N A M E DESC RIP T IO N
Debugging samples
SA M P L E N A M E DESC RIP T IO N
EEAddIn Uses the Expression Evaluator Add-In API to extend the native
debugger expression evaluator.
Fusion samples
SA M P L E N A M E DESC RIP T IO N
Hilo sample
SA M P L E N A M E DESC RIP T IO N
International samples
SA M P L E N A M E DESC RIP T IO N
DLLHusk Sharing the DLL version of the Foundation class library with
an application and custom DLL.
TestHelp An ActiveX control that has its own help file and tooltips.
Time A control that is invisible at run time and fires a timer event at
set intervals. Demonstrates notification functions and ambient
properties.
ClipArt The ClipArt directory contains sample resources that you can
use to customize the appearance of your application.
CtrlBars Custom toolbar and status bar, dialog bar, and floating
palette.
FileDlgWatcher Creates a custom dialog box that illustrates what events are
generated when you create a CFileDialog .
HelloApp Minimal MFC sample that illustrates that few lines of code are
required to get a window to appear on the screen.
Multipad Simple text editor that lets the user open and edit multiple
text files at one time.
WordPad Uses MFC's support for rich edit controls to create a basic
word processor.
TasksPane Demonstrates the MFC Task Pane classes and their different
appearances using various properties and visual managers.
TrayMenu Illustrates the ability to use MFC Control Bar menus with the
system tray icon. It's similar to the notification icons in the
lower-right corner of the display.
ODBC samples
SA M P L E N A M E DESC RIP T IO N
OS samples
SA M P L E N A M E DESC RIP T IO N
Unix samples
SA M P L E N A M E DESC RIP T IO N
Unix - ccWrapper Demonstrates a wrapper that maps flags from the Sun Forte
and gcc compilers to the Microsoft Visual C++ compiler
(cl.exe).
Windows 8 samples
The Windows 8 Sample Pack includes all the app code examples developed and updated for Windows 8. The
sample pack provides a convenient way to download all the samples at once. The samples in this sample pack are
available in C#, C++, VB.NET, and JavaScript. The Windows Samples Gallery contains code samples that exercise
the various new programming models, platforms, features, and components available in Windows 8 and Windows
Server 2012. These downloadable samples contain the Visual Studio solution (sln) file, source files, assets,
resources, and metadata necessary to compile and run successfully.
More information is available about the programming models, platforms, languages, and APIs demonstrated in
each sample. See the guidance, tutorials, and reference articles provided in the Windows 8 documentation,
available in the Windows Developer Center. These samples are provided as-is, to demonstrate the functionality of
the programming models and feature APIs for Windows 8 and Windows Server 2012.
SA M P L E N A M E DESC RIP T IO N
Background Transfer sample (Windows 8) This sample demonstrates the power-friendly, cost-aware, and
flexible behavior of the Background Transfer API for Windows
Runtime applications. Provided sample scenarios cover file
downloads and uploads.
CryptoWinRT sample (Windows 8) This sample shows how to use the new Cryptography APIs.
Print sample (Windows 8) This sample demonstrates how apps can integrate the
Windows print experience. The scenarios demonstrated in this
sample include: Printing from the app by using the charms bar
and the print contract, Printing from within the app
experience, and more.
HttpClient sample (Windows 8) This sample demonstrates the use of the HttpClient class and
the IXMLHTTPRequest2 interface to upload and download
various types of content from an HTTP server using the
networking features provided by the Windows Runtime.
Accelerometer sensor sample (Windows 8) This sample shows how to use the
Windows.Devices.Sensors.Accelerometer API. This sample
allows the user to view the acceleration forces along the X-, Y-
, and Z-axes for a 3-axis accelerometer. You can choose one of
three scenarios.
Account picture name sample (Windows 8) This sample demonstrates different ways of getting the name
of the user that is currently logged in. It also demonstrates
how to get and set the image used for the user's tile.
App settings sample (Windows 8) This sample demonstrates how to use the ApplicationSettings
API and settings flyouts to integrate an app's settings UI with
the Settings charm. The sample uses the
Windows.UI.ApplicationSettings namespace and
WinJS.UI.SettingsFlyout .
Windows Store device app for camera sample (Windows 8) This sample demonstrates how to create a Windows Store
device app for a camera. A Windows Store device app is
provided by an IHV or OEM to differentiate the capture
experience for a particular camera.
Getting started with C++ simple blog reader sample The sample demonstrates some basic principles of Windows
(Windows 8) Store app development in native C++ using XAML to define
the user interface. It's a complete working version of the
application discussed on the Windows Developer Center.
Reading and writing data sample (Windows 8) This sample shows how to use the DataReader and DataWriter
classes to store and retrieve data.
Application data sample (Windows 8) This sample shows you how to store and retrieve data that is
specific to each user and Windows Store app using the
Windows Runtime application data APIs. Application data
includes session state, user preferences, and other settings.
Custom driver access sample (Windows 8) This sample shows how to use CreateDeviceAccessInstance
and IDeviceIoControl to access a specialized device.
SA M P L E N A M E DESC RIP T IO N
XAML ListView and GridView essentials sample (Windows 8) This sample demonstrates how to use the GridView and
ListView controls.
Animation metrics sample (Windows 8) This sample shows how to use the Animation Metrics APIs in
Windows.UI.Core .AnimationMetrics to access the raw
parameters that define the animations in the Windows
Animation Library.
Playback Manager msAudioCategory sample (Windows 8) This sample demonstrates how to select the correct
msAudioCategory category for an audio-video (AV) stream to
configure it as an audio playback stream.
XAML DirectX 3D shooting game sample (Windows 8) This sample demonstrates the implementation of a simple first
person 3-D game using DirectX (Direct3D 11.1, Direct2D,
XInput, and XAudio2) and XAML in a C++ app. XAML is used
for the heads-up display and game state messages.
XAML scrolling, panning, and zooming sample (Windows 8) This sample demonstrates how to use the ScrollViewer control
to pan and zoom.
XAML FlipView control sample (Windows 8) This sample demonstrates how to use the FlipView control to
enable users to flip through a collection.
Gyrometer sensor sample (Windows 8) This sample shows how to use the
Windows.Devices.Sensors.Gyrometer API. This sample
allows the user to view the angular velocity along the X-, Y-,
and Z-axis for a 3-axis gyrometer.
Device app for printers SDK sample (Windows 8) This sample shows how to create a device app for printers that
can be activated from the tile contract, the printTaskSettings
contract, and from toast displayed by backgroundTask in
response to print driver event.
Background task sample (Windows 8) This sample shows you how to create and register background
tasks using the Windows Runtime background task API. A
background task is triggered by a system or time event, and
can be constrained by one or more conditions.
StreamSocket sample (Windows 8) This sample demonstrates the basics of the StreamSocket class
using the networking features provided by the Windows
Runtime. The client component of the sample creates a TCP
socket to make a network connection, uses the socket to send
data, and more.
Scheduled notifications sample (Windows 8) This sample shows how to use scheduled and recurring tile
updates and toast notifications for an app. This ability enables
you to specify a precise time to deliver the notification, even if
the app isn't running.
Playback Manager Companion Sample (Windows 8) This sample demonstrates how to select the correct
msAudioCategory category for an audio-video stream to
configure it as an audio playback stream.
SA M P L E N A M E DESC RIP T IO N
File access sample (Windows 8) This sample shows how to create, read, write, copy and delete
a file, how to retrieve file properties, and how to track a file or
folder so that your app can access it again. This sample uses
Windows.Storage and Windows.Storage.AccessCache API.
Removable storage sample (Windows 8) The removable storage sample demonstrates how to transfer
files to and from removable storage devices. This sample
requires a removable storage device connected to the system,
such as a camera, media player, cellular phone, or a USB
thumb drive.
XAML SurfaceImageSource DirectX interop sample (Windows This sample demonstrates how to use a
8) SurfaceImageSource to include DirectX content in your
XAML app. This sample uses both C++ and C#.
Connecting with WebSockets sample (Windows 8) This sample demonstrates how to use WebSockets in a
connected Windows Store app. The sample covers basic
functionality, such as how to make a connection, send and
receive data, and close the connection.
Configure keys for media sample (Windows 8) This sample demonstrates how to configure the hardware
media keys on a keyboard. Then, how to use the configured
keys to control an audio-video stream by pressing or clicking
play, pause, stop, and so on.
XAML personality animations sample (Windows 8) This sample demonstrates how to use the built-in personality
animations in your app.
Toast notifications sample (Windows 8) This sample shows how to use toast notifications: Ones that
appear as pop-up notifications in the upper right corner of the
screen. A user can select the toast (touch or click) to launch
the associated app.
Contact Picker app sample (Windows 8) This sample demonstrates how to use the Contact Picker to
select one or more contacts. It also includes a basic
implementation of the Contact Picker APIs to demonstrate
how to display a list of contacts to the user.
DirectX marble maze game sample (Windows 8) This sample demonstrates how to build a basic 3D game using
DirectX. This game is a simple labyrinth game where the
player is challenged to roll a marble through a maze of pitfalls
using tilt controls.
DirectX postcard app sample (Windows 8) This sample demonstrates the implementation of a simple
Windows Store app using DirectX with C++ for postcard
creation using DirectX and XAML interop.
DirectX 3D shooting game sample (Windows 8) This sample demonstrates the implementation of a simple first
person 3-D game using DirectX (Direct3D 11.1, Direct2D,
XInput, and XAudio2) in a C++ app.
SA M P L E N A M E DESC RIP T IO N
XAML AppBar control sample (Windows 8) This sample demonstrates how to use the AppBar control to
present navigation, commands, and tools to users. The app
bar is hidden by default and appears when users swipe a
finger from the top or bottom edge of the screen.
Date and time formatting sample (Windows 8) This sample demonstrates how to use the DateTimeFormatter
class in the Windows.Globalization.DateTimeFormatting
namespace to display dates and times according to the user's
preferences.
Secondary tiles sample (Windows 8) This sample shows how to pin and use a secondary tile. That's
a tile that directly accesses a specific, non-default section or
experience within an app, such as a saved game, or a specific
friend in a social networking app.
Input Touch hit testing sample (Windows 8) This sample uses a polygon shapes puzzle to demonstrate
how to handle pointer input, implement custom hit testing for
touch input, and process manipulations in a Windows Store
app using C++ and DirectX.
Network information sample (Windows 8) This sample demonstrates how to use the Windows Runtime
Network Information APIs.
Input Simplified ink sample (Windows 8) This sample demonstrates how to use ink functionality in
Windows Store apps.
StorageDataSource and GetVirtualizedFilesVector sample This sample shows how to retrieve and display images in the
(Windows 8) user's Pictures Library.
Edge-based gesture invocation sample (Windows 8) This sample shows how to listen for events that occur in edge-
based UI, using the EdgeGesture class.
Check if current session is remote sample (Windows 8) This sample demonstrates the use of
Windows.System.RemoteDesktop API.
Application resources and localization sample (Windows 8) This sample shows how to use application resources to
separate localizable content from application code. The sample
uses the Windows.ApplicationModel.Resources.Core and
Windows.Globalization namespaces, and
WinJS.Resources .
Context menu sample (Windows 8) This sample shows how to create a context menu and how to
replace the default context menu for text. This sample uses
Windows.UI.Popups API, including the PopupMenu and the
oncontextmenu event.
Geolocation sample (Windows 8) The Geolocation sample demonstrates how to use the
Geolocation API to get the geographic location of the user's
PC. An app can use the Geolocation API to get location one
time, or it can continuously track the location.
Message dialog sample (Windows 8) This sample demonstrates how to use a MessageDialog for
displaying dialogs, setting commands and their actions, and
changing the default button. The Windows.UI.Popups
namespace contains the MessageDialog class.
SA M P L E N A M E DESC RIP T IO N
MediaStreamSource media extension sample (Windows 8) This sample shows how to support the Microsoft Silverlight
MediaStreamSource concept in a Windows Store app.
DirectWrite vertical text sample (Windows 8) This sample uses DirectWrite and Direct2D to properly display
vertical text in a custom layout shape.
DXGI swap chain rotation sample (Windows 8) This sample demonstrates the IDXGISwapChain1::SetRotation
method and how you can use the method in conjunction with
prerotated content to improve presentation performance.
Direct2D custom image effects sample (Windows 8) This sample demonstrates how to implement custom Direct2D
Effects using standard pixel, vertex, and compute shaders.
DirectX touch input sample (Windows 8) This sample demonstrates touch and mouse navigation of a
3-D environment in a C++ app with Direct3D.
XInput game controller sample (Windows 8) This sample demonstrates the use of the XInput APIs in a
C++ app. It reads input from an Xbox game controller and
displays data about the analog stick movements and button
presses.
Direct3D-Direct2D interop sample (Windows 8) This sample shows how to interoperate with Direct2D and
DirectWrite to write text to a Direct3D render target. It's an
effective way to create heads-up displays and text-based
readouts such as scoring panels in games and 3-D apps.
Syndication sample (Windows 8) This sample demonstrates a basic Windows Store app for
Windows 8 that can retrieve feeds from a web service. This
sample is currently provided in the JavaScript, C#, C++, and
VB programming languages.
App tiles and badges sample (Windows 8) This sample shows how to use an app tile, which is the
representation and launch point for your app in the Start
screen. It also shows how to use a badge on that tile. It's a
method for the app to relay status information to the user
when the app isn't running.
XAML user and custom controls sample (Windows 8) This sample demonstrates how to create and use XAML
UserControl elements and create custom controls for your
projects.
Direct3D resource loading sample (Windows 8) This sample demonstrates Direct3D resource loading for C++
apps with DirectX.
XAML ListView and GridView customizing interactivity sample This sample demonstrates the interaction model of the
(Windows 8) ListView control.
XAML WebView control sample (Windows 8) This sample demonstrates how to use the WebView control
to display a URL, load HTML, interact with script within a
WebView , and use WebViewBrush .
Compass sensor sample (Windows 8) This sample demonstrates how to use the
Windows.Devices.Sensors.Compass API. This sample allows
the user to view the compass reading as a magnetic-north
and, depending on the installed sensor, a true-north value.
SA M P L E N A M E DESC RIP T IO N
Display orientation sample (Windows 8) This sample demonstrates how to use the
DisplayProperties class to set the display orientation in an
app.
Direct2D interpolation modes sample (Windows 8) This sample shows the various interpolation modes used by
Direct2D.
Globalization preferences sample (Windows 8) This sample demonstrates how to use the
Windows.System.UserProfile.GlobalizationPreferences
class to obtain the user's globalization preferences. It also
shows how to use the GeographicRegion and Language
classes.
Direct2D geometry realization sample (Windows 8) This sample shows how multi-core geometry tessellation can
help reduce geometry rendering time. Using opacity masks
and meshes is an alternative to traditional geometry
rendering that may be better in some situations.
Language font mapping sample (Windows 8) This sample demonstrates how to obtain language-specific
font recommendations using the LanguageFontGroup class in
the Windows.Globalization.Fonts namespace.
Inclinometer sensor sample (Windows 8) This sample shows how to use the
Windows.Devices.Sensors.Inclinometer API. This sample
allows the user to view the angles of incline about the X-, Y-,
and Z-axis for a 3-axis inclinometer.
XAML high contrast style sample (Windows 8) This sample demonstrates various techniques for
implementing support for high contrast mode in your app.
Support for high contrast mode is important to make your
app accessible to people with eyesight problems.
Input Device capabilities sample (Windows 8) This sample demonstrates how to query the input devices
that are connected to the user's device. And, how to support
the pointer, touch, pen/stylus, mouse, and keyboard input
modes of Windows Store apps.
EAS policies for mail clients sample (Windows 8) This sample shows how mail clients can retrieved device
information and work with supplied Exchange Active Sync
(EAS) policies. Windows Store apps can configure their mail
clients to stay compliant with the given EAS policies.
DatagramSocket sample (Windows 8) This sample demonstrates the basics of the DatagramSocket
class using the networking features provided by the Windows
Runtime. The client component of the sample creates a UDP
socket, uses the socket to send and receive data, and closes
the socket.
DirectWrite hello world sample (Windows 8) This sample shows how to use DirectWrite and Direct2D to
render the text "Hello World" to a CoreWindow .
Compression sample (Windows 8) This sample demonstrates how to read structured data from a
file and write compressed data to a new file and how to read
compressed data and write decompressed data to a new file.
Many applications need to compress and decompress data.
SA M P L E N A M E DESC RIP T IO N
Network status background sample (Windows 8) This sample demonstrates how to determine a change in
Internet connection profile by registering a background task
handler for Network Status Change event using an Internet
Present condition.
App package information sample (Windows 8) This sample shows you how to get package information using
the Windows Runtime packaging API. Users acquire your
Windows Store app as an app package. Windows uses the
information in an app package to install the app on a per-user
basis.
Mobile broadband account provisioning sample (Windows 8) This sample demonstrates how to use the Windows 8 Mobile
Broadband provisioning agent API (
Windows.Networking.NetworkOperators.ProvisioningAgent
) to configure Windows 8 with required connectivity
information and access provisioning.
Media Play To sample (Windows 8) This sample demonstrates the Play To API. It shows how you
can expand your media application to stream video, audio,
and images to other devices on your local network.
Input Touch keyboard sample (Windows 8) This sample demonstrates how to launch the touch keyboard
automatically in custom controls that aren't derived from
platform controls. The sample implements custom controls
that require keyboard input and aren't derived from standard
XAML controls.
XAML animation library sample (Windows 8) This sample demonstrates how to animate elements and apply
easing functions to the animations to achieve various effects.
Snap sample (Windows 8) The snapped state is one of the four possible application view
states. Snapping an app resizes the app to 320 pixels wide,
which allows it to share the screen with another app. Snapping
enables two apps to be visible at the same time.
Transcoding media sample (Windows 8) This sample demonstrates how to use the
Windows.Media.Transcoding API to transcode a video file in
a Windows Store app. Transcoding is the conversion of a
digital media file, such as a video or audio file, from one
format to another.
XAML two-dimensional transforms sample (Windows 8) This sample demonstrates how to use two-dimensional
transforms to modify how elements are displayed in your app.
A transform defines how to map, or transform, points from
one coordinate space to another coordinate space.
SA M P L E N A M E DESC RIP T IO N
IXmlReader and IXmlWriter XML data read write sample This sample demonstrates how to use IXmlReader and
(Windows 8) IXmlWriter in your Windows Store app with C++. They're
used to read and write XML data from a flat XML-formatted
text file. These interfaces are part of the Windows Win32 and
COM APIs, but are supported by the Windows Runtime.
Media capture using capture device sample (Windows 8) This sample demonstrates how to use the MediaCapture API
to capture video, audio, and pictures from a capture device,
such as a webcam.
XAML Popup sample (Windows 8) This sample demonstrates how to create and use the XAML
Popup element in your projects.
XAudio2 audio file playback sample (Windows 8) This sample demonstrates the use of XAudio2 in an app.
Hilo C++ sample (Windows 8) This sample demonstrates how to build a complete Windows
Store app using C++ and XAML. The Hilo photo sample
provides guidance to C++ developers that want to create a
Windows 8 app using modern C++, XAML, and the Windows
Runtime.
DirectWrite custom text renderer sample (Windows 8) This sample shows how to implement a custom text renderer
for DirectWrite.
DirectWrite font enumeration sample (Windows 8) This sample shows how to use DirectWrite to list the fonts in
the system font collection on a user's device.
Direct2D perspective transform sample (Windows 8) This sample shows how to use the DrawBitmap API to
display an image with a perspective transform applied to it.
CameraOptionsUI Sample (Windows 8) This sample demonstrates how to use camera options in a
device app. The CameraOptionsUI API displays a UI for
adjusting camera settings. This sample requires a webcam.
XInput audio controller playback sample (Windows 8) This sample demonstrates XAudio2 playback to an XInput
device, such as a headset, in an app.
Direct2D 3D transform effect sample (Windows 8) This sample demonstrates the different methods to transform
an image in 3-D space.
Windows account authorization sample (Windows 8) This sample demonstrates how to use the members of the
Windows.Security.Authentication.OnlineId namespace to
authenticate a user with their Microsoft Account in delegation
mode. And, how to send acquired tokens to Live Connect APIs
using REST protocol.
SA M P L E N A M E DESC RIP T IO N
Number formatting and parsing sample (Windows 8) This sample demonstrates how to use the
DecimalFormatter , CurrencyFormatter ,
PercentFormatter , and PermilleFormatter classes in the
Windows.Globalization.NumberFormatting namespace.
They're used to display and parse numbers, currencies, and
percent values.
DXGI offer and reclaim resources sample (Windows 8) This sample demonstrates the use of the DXGI
IDXGIDevice2::OfferResources and
IDXGIDevice2::ReclaimResources APIs in a C++ app with
DirectX.
Web authentication broker sample (Windows 8) This sample demonstrates the web authentication broker
WinRT API. It lets you enable single sign-on (SSO) connections
to OAuth providers such as Facebook, Google, Microsoft, and
Twitter.
XAudio2 audio stream effect sample (Windows 8) This sample demonstrates audio streaming in a C++ app
using the XAudio2 and Media Foundation APIs.
Splash screen sample (Windows 8) This sample shows how to imitate the splash screen that
Windows displays for your app, by positioning a similar image
correctly when Windows dismisses the splash screen that it
displays.
SMS background task sample (Windows 8) This sample shows how to use the Windows 8 Mobile
Broadband SMS API ( Windows.Devices.Sms ) with the
Background Task API (
Windows.ApplicationModel.Background ) to send and
receive SMS text messages.
SMS message send, receive, and SIM management sample This sample shows how to use the Windows 8 Mobile
(Windows 8) Broadband SMS API ( Windows.Devices.Sms ).
Trial app and in-app purchase sample (Windows 8) This sample demonstrates how to use the licensing API
provided by the Windows Store to determine the license
status of an app, or of a feature enabled by an in-app
purchase.
Input Touch keyboard text input sample (Windows 8) This sample shows how to enable optimized views on the
touch keyboard. It works by using input scopes and input
types with controls in the WinJS.UI namespace, and with
the TextBox and RichEdit XAML controls.
XAML text editing sample (Windows 8) This sample demonstrates how to use text input controls in
your app.
Thread pool sample (Windows 8) This sample shows you how to run work items asynchronously
using the Windows Runtime thread pool API.
UI Automation core window provider sample (Windows 8) This sample demonstrates how to create a Microsoft UI
Automation provider. It makes programmatic information
about a Windows Store app available to accessible
technologies such as screen readers. The sample is a Direct2D
application.
SA M P L E N A M E DESC RIP T IO N
XAML accessibility sample (Windows 8) This sample shows you how to add basic accessibility support
to your app.
Playlist sample (Windows 8) This sample demonstrates how to create, save, display, and
edit a playlist of audio files. This sample uses classes that are in
the Windows.Media.Playlists namespace.
Media Server client sample (Windows 8) This sample demonstrates how to create a Media Server client
using the Media Server API. The Media Server sample
demonstrates how to browse a Digital Media Server
programmatically on your local network, and display all of its
video files.
Direct2D magazine app sample (Windows 8) This sample shows how to use Direct2D, DirectWrite, Windows
Imaging Component (WIC), and XAML to build an app with a
magazine-type presentation.
Mobile broadband account and device management sample This sample shows how to use the Windows 8 Mobile
(Windows 8) Broadband API ( Windows.Networking.NetworkOperators )
employed by Mobile Network Operators (MNO). It
demonstrates how to use the MobileBroadbandAccount APIs
to retrieve and display available Mobile Broadband accounts.
Proximity sample (Windows 8) This sample demonstrates how to use the PeerFinder and
ProximityDevice classes to communicate with nearby
computers. You can use the Proximity API to exchange
small messages during a tap gesture or set up a socket
connection between peer apps.
Creating a Windows Runtime in-process component sample This sample shows how to create a component in C++/CX
(C++CX) (Windows 8) that's used in C++/CX, JavaScript, and C# client code. The
OvenServer project contains a runtime class named Oven ,
which implements an IOven interface and an IAppliance
interface.
Device auto rotation preferences sample (Windows 8) This sample shows how to use the DisplayProperties class
to handle and verify device rotation events.
Real-time communication sample (Windows 8) This sample demonstrates how to use the low latency feature
to enable real-time communication applications.
Sharing content source app sample (Windows 8) This sample demonstrates how an app can share content with
another app. This sample uses classes from the
Windows.ApplicationModel.DataTransfer namespace.
Search contract sample (Windows 8) This sample shows how to let users search your app when
they select the Search charm and open the search pane. And,
how to use the search pane to display suggestions for users'
queries.
Raw notifications sample (Windows 8) This sample shows how to use raw notifications, which are
push notifications with no associated UI that perform a
background task for the app.
SA M P L E N A M E DESC RIP T IO N
Direct2D basic image effects sample (Windows 8) This sample shows how to load an image, apply the Gaussian
blur effect to it, and then display it in a
Windows::UI::Core::CoreWindow .
Direct2D effects on primitives sample (Windows 8) This sample shows how to apply image effects to Direct2D
primitives. This sample draws rounded rectangles using
Direct2D and then draws DirectWrite text in the middle of the
rectangles. Then it applies an effect graph to it.
ControlChannelTrigger StreamSocket sample (Windows 8) The sample shows how to use the ControlChannelTrigger
class in a Windows Store app. It uses a TCP StreamSocket , so
the app is always connected and always reachable. This sample
demonstrates the use of background network notifications.
ControlChannelTrigger StreamWebSocket sample (Windows 8) The sample shows how to use the ControlChannelTrigger
class to enable a Windows Store app using a
StreamWebSocket to be always connected and always
reachable. This sample demonstrates the use of background
network notifications.
Association launching sample (Windows 8) This sample shows you how to launch the user's default app
for file type or a protocol. You can also learn how to enable
your app to be the default app for a file type or a protocol.
AtomPub sample (Windows 8) This sample demonstrates how to access, create, update, and
remove syndicated content feeds from the web. It uses the
Windows Runtime implementation of the Atom Publication
standard.
Certificate enrollment sample (Windows 8) This sample demonstrates how to create and enroll a
certificate in a certification hierarchy. To obtain an evaluation
copy of Windows 8, go to Windows 8. To obtain an evaluation
copy of Microsoft Visual Studio 2012, go to Visual Studio
2012.
Clipboard app sample (Windows 8) This sample demonstrates how an app can use clipboard
commands, including copy, paste, cut, and move. This sample
uses classes from the
Windows.ApplicationModel.DataTransfer namespace.
Direct2D composite effect modes sample (Windows 8) This sample shows the wide range of composite and blend
modes available from Direct2D.
Direct3D bump mapping sample (Windows 8) This sample demonstrates bump mapping using a normal
map and per-pixel lighting.
Calendar details and math sample (Windows 8) This sample demonstrates how to use the Calendar class in
the Windows.Globalization namespace to manipulate and
process dates based on a calendar system and the user's
globalization preferences.
Device enumeration sample (Windows 8) This sample shows how to use the Device Enumeration API to
find available devices and look for device information. The
sample presents two scenarios: In the first scenario, the Device
Enumeration API is used to look for specific device interfaces.
SA M P L E N A M E DESC RIP T IO N
DirectWrite paragraph text sample (Windows 8) This sample shows how to use DirectWrite and Direct2D to
render paragraph text to a CoreWindow . And, apply
justification and character spacing to the layout.
Responding to the appearance of the on-screen keyboard [This documentation is preliminary and is subject to change.]
sample (Windows 8) This sample shows how to listen for and respond to the
appearance of the onscreen soft keyboard. When focus is
given to an element that requires text input on a device that
doesn't have a keyboard.
XAML data binding sample (Windows 8) This sample demonstrates basic data binding techniques using
the Binding class and Binding markup extension.
Direct3D tutorial sample (Windows 8) This sample is a five-lesson tutorial. It provides an introduction
to the Direct3D API, and introduces the concepts and code
used in many of the other DirectX samples.
Direct2D effects photo adjustment app sample (Windows 8) This sample shows various common photo manipulation
techniques using Direct2D Effects. This sample is divided into
several parts. Lesson 1: Shows the basics of loading and
drawing an image using Direct2D Effects.
Windows Audio Session (WASAPI) sample (Windows 8) Demonstrates how to do various audio related tasks using the
Windows Audio Session API (WASAPI).
User domain name sample (Windows 8) This sample demonstrates the domain-related functionality
provided by the UserInformation class of the
Windows.System.UserProfile namespace. The
UserInformation class enables an app to get and set
information about the user.
USSD message management sample (Windows 8) This sample demonstrates network account management
using the USSD protocol with GSM-capable mobile broadband
devices. USSD is typically used for account management of a
mobile broadband profile by the Mobile Network Operator
(MNO).
Bing Maps Trip Optimizer sample (Windows 8) The sample demonstrates how to use JavaScript and Visual
C++ and to create app for Windows 8 named Bing Maps Trip
Optimizer. Bing Maps Trip Optimizer uses JavaScript to define
the UI, and C++ for a computationally expensive algorithm in
parallel.
Direct2D and DirectWrite animated text on a path sample This sample shows how to use Direct2D and DirectWrite to
(Windows 8) render a string of text along an animated, non-linear
geometric path. The app renders "Hello, World!" repeated
several times in different languages along a Bezier curve.
Wi-Fi hotspot authentication sample (Windows 8) This sample demonstrates how to use the Windows 8 Mobile
Broadband API ( Windows.Networking.NetworkOperators ) for
Wi-Fi hotspot authentication. Use this mechanism as an
alternative to configuring static credentials for a Wi-Fi hotspot.
XAML images sample (Windows 8) This sample demonstrates various techniques for displaying
and manipulating images in your app using the Image control
and the BitmapImage class.
SA M P L E N A M E DESC RIP T IO N
HomeGroup app sample (Windows 8) This sample demonstrates how to use a HomeGroup to open,
search, and share files. This sample uses some of the
HomeGroup options found in the Windows.Storage.Pickers
and Windows.Storage.KnownFolders .
UI contrast and settings sample (Windows 8) This sample shows how to use the UI settings APIs in a basic
C# or JavaScript app.
Folder enumeration sample (Windows 8) This sample shows how to list the top-level files and folders
inside a location. (For example, a folder, device, or network
location.) And, how to use queries to list all files inside a
location by sorting them into file groups.
File picker sample (Windows 8) This sample shows how to access files and folders by letting
the user choose them through the file pickers. And, how to
save a file so that the user can specify the name, file type, and
location of a file to save.
File picker contracts sample (Windows 8) This sample shows how an app can provide files, a save
location, and real-time file updates to other apps through the
file picker. It's done by participating in the File Open Picker
contract, File Save Picker contract, and Cached File Updater
contract.
Programmatic file search sample (Windows 8) This sample shows how to query files in locations such as a
folder, library, device, or network location. It uses
Windows.Storage.Search API. Important APIs in this sample
include: QueryOptions class, StorageFileQueryResult
class, and others.
File and folder thumbnail sample (Windows 8) This sample shows how to retrieve thumbnails for files and
folders. It uses Windows.Storage.FileProperties API.
Input Manipulations and gestures (C++) sample (Windows 8) This sample demonstrates how to handle pointer input and
process manipulations and gestures with the
GestureRecognizer APIs in a Windows Store app using C++
and DirectX.
Direct3D HLSL fractal generator sample (Windows 8) This sample demonstrates the use of Direct3D HLSL and
DirectCompute compute shaders to create fractal images.
XAML Direct2D lighting effects sample (Windows 8) This sample demonstrates the lighting effects available in
Direct2D Effects. The lighting effect properties are controlled
by XAML interface controls and then displayed using Direct2D
via a XAML SwapChainBackgroundPanel.
Direct2Dapp printing sample (Windows 8) This sample demonstrates how to add Direct2D printing
support to a Windows Store app. This sample shows how to
use Direct2D features to render the content of a Windows
Store app for printing. And, how to send the rendered content
to the printer.
Direct2D printing images and effects sample (Windows 8) This sample demonstrates how to print Direct2D images and
Direct2D effects in a Windows Store app.
SA M P L E N A M E DESC RIP T IO N
Direct2D animated text sample (Windows 8) This sample shows how to render text quickly by using the
Direct2D FillOpacityMask method. The sample also
responds to touch. A two finger pinch can be used to zoom
the text in and out.
Direct3D post-processing effects sample (Windows 8) This sample demonstrates Direct3D 11.1 post-processing on a
simple rotating cube scene, using down-scaled intermediate
buffers.
Extended Linguistic Services (ELS) sample (Windows 8) This sample demonstrates the use of Extended Linguistic
Services (ELS) in a Windows Store app. The sample implements
scenarios that demonstrate the use of the three available ELS
services. The scenarios demonstrate how to request a specific
service.
DirectWrite hit testing sample (Windows 8) This sample shows how to use the hit-testing features of
DirectWrite. They're used to determine which part of the
displayed text is being clicked or touched.
DirectWrite inline object sample (Windows 8) This sample shows how to insert an inline object into a text
layout, such as an image.
XAML vector-based drawing sample (Windows 8) This sample demonstrates how to draw vector-based graphics
in your app.
Bluetooth call control sample (Windows 8) The Bluetooth CallControl sample demonstrates how to
configure the default Bluetooth communications device for
handling calls. There are JavaScript, C#, C++, and VB.Net
versions of this sample. This sample requires knowledge of
Windows events and event handling.
Direct2D command list sample (Windows 8) This sample demonstrates the use of a command list. It's used
for recording a set of vector commands, creating an image
brush from the command list, and then filling a rectangle
geometry with it. The command list preserves resolution
independence of the vector.
ControlChannelTrigger XMLHTTPRequest sample (Windows 8) The sample shows how to use the ControlChannelTrigger
class to enable a Windows Store app using
IXMLHTTPRequest2 to be always connected and always
reachable. This sample demonstrates the use of background
network notifications in a Windows Store app.
XInput and JavaScript controller sketch sample (Windows 8) This sample demonstrates how to wrap the XInput C++ API in
a Windows Runtime component. Then, it calls it from a
Windows Store app using JavaScript. This sample implements
a sketch app that lets you use the Xbox game controller to
select line thickness and more.
Direct2D convolve matrix effect sample (Windows 8) This sample demonstrates the Direct2D Effects convolve
matrix effect. This sample has some example convolution
kernel matrices: Passthrough (no-op), Box blur (width 5),
Simple edge detect, Simple sharpen, Emboss, Vertical smear
(height 10) theses and more.
SA M P L E N A M E DESC RIP T IO N
DirectX swap chain implementation sample (Windows 8) This sample shows how to receive CoreWindow events in a
native application, and how to connect a DirectX swap chain
to the application view.
Credential picker sample (Windows 8) This sample shows how to use the
Windows.Security.Credentials.UI.CredentialPicker class
to retrieve credentials. These credentials may be passed to
APIs that require them, for example, HttpClient .
Direct2D animation sample (Windows 8) This sample shows how to use Direct2D to render and
animate a Direct2D primitive along a spiral path.
Sharing content target app sample (Windows 8) This sample demonstrates how an app can receive content
shared from another app. This sample uses classes from the
Windows.ApplicationModel.DataTransfer and
Windows.ApplicationModel.DataTransfer.Share
namespaces.
Direct2D save to image file sample (Windows 8) This sample shows how to render to the screen using
Direct2D and DirectWrite. And, how to save the rendered
image to disk using the WIC API.
Scaling according to DPI sample (Windows 8) This sample describes how to build an app that scales
according to the pixel density of the screen. It loads images of
the right scale or overrides default scaling. This sample uses
the Windows.Graphics.Display API.
Creating a Windows Runtime in-process component sample This sample shows how to create a component in C# that's
(C#) (Windows 8) used in C++/CX, JavaScript, and C# client code. The
OvenServer project contains a runtime class named Oven ,
which implements an IOven interface and an IAppliance
interface.
Push and periodic notifications client-side sample (Windows 8) This sample shows how a client app can register and listen for
push notifications sent from a web server. Push notifications
can be used to update a badge or a tile, raise a toast
notification, or launch a background task.
Portable device API sample (Windows 8) This sample shows how to access the IPortableDevice
COM API from a C++ app. To learn how to access the
IPortableDevice COM API from a Desktop C++ app, refer
to the Portable Devices COM API Sample.
PlayToReceiver sample (Windows 8) This sample demonstrates how to create a software Play To
receiver. To advertise the software Play To Receiver, click the
Start Receiver button. To stop the receiver, click the Stop
Receiver button.
Lock screen personalization sample (Windows 8) This sample demonstrates how to use the LockScreen API
to set the current user's lock screen image. This sample uses
classes from the Windows.System.UserProfile namespace.
SA M P L E N A M E DESC RIP T IO N
Credential locker sample (Windows 8) This sample demonstrates how to use the WinRT
PasswordVault APIs, and how to use the credential locker to
store web credentials. Specific scenarios include a single user
with a single resource, and multiple users with a single
resource.
Media engine native C++ video playback sample (Windows 8) This sample demonstrates video playback using the
MediaEngine API in a native C++ app.
Media extensions sample (Windows 8) This sample demonstrates how to use media extensions. You
can apply effects to video, decode video, and create media
streams using scheme handlers.
Lock screen apps sample (Windows 8) This sample shows how an app can have a presence on the
lock screen—the screen that is shown when the computer is
locked—with a badge to provide basic status information or a
tile to provide more detailed status.
XAML text display sample (Windows 8) This sample demonstrates how control the appearance of text
in your app.
Direct3D sprite sample (Windows 8) This sample provides a Direct3D implementation of sprite
batch behaviors, similar to the XNA SpriteBatch API. Sprites
are 2-D bitmaps that can be transformed and managed
independently in a 3-D scene, typically used in 2-D games.
Direct3D stereoscopic 3D sample (Windows 8) This sample demonstrates how to add a stereoscopic 3-D
effect to C++ apps by using Direct3D. It also demonstrates
how to respond to system stereo changes in Direct3D. The
stereoscopic 3-D effect requires a display that supports stereo
3-D.
Creating a Windows Runtime DLL component with C++ This sample shows how to create an in-process DLL
sample (Windows 8) component in Microsoft Visual C++. It's used in C++/CX,
JavaScript, and C# client code. The OvenServer project
contains a runtime class named Oven , which implements an
IOven interface.
Creating a Windows Runtime EXE component with C++ This sample shows how to create an out-of-process EXE
sample (Windows 8) component in Microsoft Visual C++. It's used in C++/CX,
JavaScript, and C# client code. The OvenServer project
contains a runtime class named Oven , which implements an
IOven interface.
Microsoft C/C++ help and community
12/18/2020 • 2 minutes to read • Edit Online
Here's where to get help and information about how to write C++ code and use the Visual Studio development
tools.
Samples
Developer Code Samples: Contains downloadable sample code from Microsoft and community contributors.
Product documentation
C++ in Visual Studio: Contains reference and conceptual documentation about Visual C++.
Windows Developer Center: Contains information about how to use C++ and other languages to develop
apps for Windows 10.
Online and offline documentation
You can view Microsoft developer content online. This content is updated regularly.
You can also download and view the content locally in the offline Help Viewer. The offline documentation is
organized by books of related content, which are also updated periodically. You can download the books you are
interested in as they become available. For more information, see Microsoft Help Viewer.
Many sections of the documentation are also available in PDF form. These sections have a Download PDF link
below the table of contents on docs.microsoft.com.
Related sites
C++ Team Blog: Contains posts on various subjects by the experts on Microsoft's C++ product team.
Channel 9: Contains video interviews and lectures. Use the search box on the Channel 9 home page to find
C++ content.
Visual Studio website: Contains articles and news about Visual Studio and related development tools. This
site also hosts Visual Studio downloads and redistributable files.
Microsoft Docs Q&A: Official Microsoft forums where you can post questions about C++ and Visual Studio
and get answers from Microsoft and from experts in the community.
Visual Studio C++ Developer Community: Forums for reporting problems in the C++ compiler and tools or
the IDE, or for making product suggestions. You can vote for your favorite ideas or bug reports, or add a new
one. This site is monitored by the development team.
How to report a problem with the Microsoft C++
toolset or documentation
12/18/2020 • 25 minutes to read • Edit Online
If you find problems in the Microsoft C++ compiler (MSVC), the linker, or other tools and libraries, we want to
know about them. When the issue is in our documentation, we want to know about that, too.
Compiler Passes:
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\cl.exe: Version 19.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\c1.dll: Version 19.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\c1xx.dll: Version 19.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\c2.dll: Version 19.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\link.exe: Version 14.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\mspdb140.dll: Version 14.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\1033\clui.dll: Version 19.14.26428.1
Add any other details that might help us diagnose the problem you found, such as any work-arounds you've
discovered. Try not to repeat information found elsewhere in your report.
The repro
A repro is a complete, self-contained source code example. It reproducibly demonstrates the problem you've found,
hence the name. We need a repro so that we can reproduce the error on our machines. The code should be
sufficient by itself to create a basic executable that compiles and runs. Or, that would compile and run, if not for the
problem you've found. A repro isn't a code snippet. It should have complete functions and classes, and contain all
the necessary #include directives, even for the standard headers.
What makes a good repro
A good repro is:
Minimal. Repros should be as small as possible yet still demonstrate exactly the problem you found. Repros
don't need to be complex or realistic. They only need to show code that conforms to the Standard, or to the
documented compiler implementation. For a missing diagnostic, your repro should show the code that's not
conformant. Simple, to-the-point repros that contain only enough code to demonstrate the problem are
best. If you can eliminate or simplify the code and remain conformant, and also leave the issue unchanged,
then do so. You don't need to include counter-examples of code that works.
Self-Contained. Repros should avoid unnecessary dependencies. If you can reproduce the problem
without third-party libraries, then do so. If you can reproduce the problem without any library code besides
simple output statements (for example, puts("this shouldn't compile"); , std::cout << value; , and
printf("%d\n", value); ), then do so. It's ideal if the example can be condensed to a single source code file,
without reference to any user headers. Reducing the amount of code we have to consider as a possible
contributor to the problem is enormously helpful to us.
Against the latest compiler version. Repros should use the most recent update to the latest version of
the toolset whenever possible. Or, use the most recent prerelease version of the next update or next major
release. Problems you may find in older versions of the toolset have often been fixed in newer versions.
Fixes are backported to older versions only in exceptional circumstances.
Checked against other compilers if relevant. Repros that involve portable C++ code should verify
behavior against other compilers if possible. The C++ standard ultimately determines program correctness,
and no compiler is perfect. However, when Clang and GCC accept your code without a diagnostic, and MSVC
doesn't, you've probably found a bug in our compiler. (Other possibilities include differences in Unix and
Windows behavior, or different levels of C++ standards implementation, and so on.) When all the compilers
reject your code, then it's likely that your code is incorrect. Seeing different error messages may help you
diagnose the issue yourself.
You can find lists of online compilers to test your code against in Online C++ compilers on the ISO C++
website, or this curated List of Online C++ Compilers on GitHub. Some specific examples include Wandbox,
Compiler Explorer, and Coliru.
NOTE
The online compiler websites are not affiliated with Microsoft. Many online compiler websites are run as personal
projects. Some of these sites may be unavailable when you read this, but a search should find others you can use.
Problems in the compiler, linker, and in the libraries, tend to show themselves in particular ways. The kind of
problem you find will determine what kind of repro you should include in your report. Without an appropriate
repro, we have nothing to investigate. Here are a few of the kinds of issues that you may see. We include
instructions on how to generate the kind of repro you should use to report each kind of problem.
Frontend (parser) crash
Frontend crashes occur during the parsing phase of the compiler. Typically, the compiler emits Fatal Error C1001,
and references the source code file and line number on which the error occurred. It often mentions a file named
msc1.cpp, but you can ignore this detail.
For this kind of crash, provide a Preprocessed repro.
Here's example compiler output for this kind of crash:
SandBoxHost.cpp
d:\o\dev\search\foundation\common\tools\sandbox\managed\managed.h(929):
fatal error C1001: An internal error has occurred in the compiler.
(compiler file 'msc1.cpp', line 1369)
To work around this problem, try simplifying or changing the program near the
locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
d:\o\dev\search\foundation\common\tools\sandbox\managed\managed.h(929):
note: This diagnostic occurred in the compiler generated function
'void Microsoft::Ceres::Common::Tools::Sandbox::SandBoxedProcess::Dispose(bool)'
Internal Compiler Error in d:\o\dev\otools\bin\x64\cl.exe. You will be prompted
to send an error report to Microsoft later.
INTERNAL COMPILER ERROR in 'd:\o\dev\otools\bin\x64\cl.exe'
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
repro.cpp
\\officefile\public\tadg\vc14\comperror\repro.cpp(13) : fatal error C1001:
An internal error has occurred in the compiler.
(compiler file 'f:\dd\vctools\compiler\utc\src\p2\main.c', line 230)
To work around this problem, try simplifying or changing the program near the
locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
INTERNAL COMPILER ERROR in
'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe'
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
If the line that begins with INTERNAL COMPILER ERROR mentions link.exe, rather than cl.exe, LTCG was enabled.
Provide a Link repro in this case. When it's not clear whether LTCG was enabled from the compiler error message,
examine the command-line arguments. You copied them from your build log, in a previous step for the /GL
command-line argument.
Linker crash
Linker crashes occur during the linking phase, after the compiler has run. Typically, the linker will emit Linker Tools
Error LNK1000.
NOTE
If the output mentions C1001 or involves Link-Time Code Generation, refer to Backend (code generation) crash instead.
Version 14.00.22816.0
ExceptionCode = C0000005
ExceptionFlags = 00000000
ExceptionAddress = 00007FF73C9ED0E6 (00007FF73C9E0000)
"z:\tools\bin\x64\link.exe"
NumberParameters = 00000002
ExceptionInformation[ 0] = 0000000000000000
ExceptionInformation[ 1] = FFFFFFFFFFFFFFFF
CONTEXT:
If incremental linking is enabled, and the crash occurred only after a successful initial link, that is, only after the first
full link on which a later incremental link is based, also provide a copy of the object (.obj) and library (.lib) files that
correspond to source files modified after the initial link was completed.
Bad code generation
Bad code generation is rare. It occurs when the compiler mistakenly generates incorrect code that causes your
application to crash at runtime. Instead, it should generate correct code, or detect a problem at compile time. If you
believe the problem you've found results in bad code generation, treat your report the same as a Backend (code
generation) crash.
For this kind of crash, provide a Link repro if you're using the /GL command-line argument to cl.exe. Provide a
Preprocessed repro if not.
NOTE
Preprocessed repros are not as useful for problems that might be the result of bugs in our standard library implementation,
because we will often want to substitute our latest, in-progress implementation to see whether we've already fixed the
problem. In this case, don't preprocess the repro, and if you can't reduce the problem to a single source file, package your
code into a .zip file or similar, or consider using an IDE project repro. For more information, see Other repros.
NOTE
Regardless of how you submit your report, Microsoft respects your privacy. Microsoft is committed to compliance with all
data privacy laws and regulations. For information about how we treat the data that you send us, see the Microsoft Privacy
Statement.
TIP
For other kinds of problems you might find in Visual Studio that are unrelated to the C++ toolset (For example, UI issues,
broken IDE functionality, or general crashes), use the Repor t a Problem tool in the IDE. This is the best choice, due to its
screenshot capabilities and its ability to record UI actions that lead to the problem you've found. These kinds of errors can
also be looked up on the Visual Studio Developer Community site. For more information, see How to report a problem with
Visual Studio.
If you haven't downloaded and installed Visual Studio and the Microsoft C/C++ tools yet, here's how to get
started.
NOTE
This topic applies to installation of Visual Studio on Windows. Visual Studio Code is a lightweight, cross-platform
development environment that runs on Windows, Mac, and Linux systems. The Microsoft C/C++ for Visual Studio Code
extension supports IntelliSense, debugging, code formatting, auto-completion. Visual Studio for Mac doesn't support
Microsoft C++, but does support .NET languages and cross-platform development. For installation instructions, see Install
Visual Studio for Mac.
Want to know more about what else is new in this version? See the Visual Studio release notes.
Ready to install? We'll walk you through it, step-by-step.
Step 1 - Make sure your computer is ready for Visual Studio
Before you begin installing Visual Studio:
1. Check the system requirements. These requirements help you know whether your computer supports
Visual Studio 2019.
2. Apply the latest Windows updates. These updates ensure that your computer has both the latest security
updates and the required system components for Visual Studio.
3. Reboot. The reboot ensures that any pending installs or updates don't hinder the Visual Studio install.
4. Free up space. Remove unneeded files and applications from your %SystemDrive% by, for example, running
the Disk Cleanup app.
For questions about running previous versions of Visual Studio side by side with Visual Studio 2019, see the Visual
Studio 2019 Platform Targeting and Compatibility page.
Step 2 - Download Visual Studio
Next, download the Visual Studio bootstrapper file. To do so, choose the following button to go to the Visual Studio
download page. Select the edition of Visual Studio that you want and choose the Free trial or Free download
button.
D O W NLO AD VISU AL
S TU D IO
For core C and C++ support, choose the "Desktop development with C++" workload. It comes with the
default core editor, which includes basic code editing support for over 20 languages, the ability to open and
edit code from any folder without requiring a project, and integrated source code control.
Additional workloads support other kinds of development. For example, choose the "Universal Windows
Platform development" workload to create apps that use the Windows Runtime for the Microsoft Store.
Choose "Game development with C++" to create games that use DirectX, Unreal, and Cocos2d. Choose
"Linux development with C++" to target Linux platforms, including IoT development.
The Installation details pane lists the included and optional components installed by each workload. You
can select or deselect optional components in this list. For example, to support development by using the
Visual Studio 2017 or 2015 compiler toolsets, choose the MSVC v141 or MSVC v140 optional components.
You can add support for MFC, the experimental Modules language extension, IncrediBuild, and more.
2. After you choose the workload(s) and optional components you want, choose Install .
Next, status screens appear that show the progress of your Visual Studio installation.
TIP
At any time after installation, you can install workloads or components that you didn't install initially. If you have Visual
Studio open, go to Tools > Get Tools and Features... which opens the Visual Studio Installer. Or, open Visual Studio
Installer from the Start menu. From there, you can choose the workloads or components that you wish to install. Then,
choose Modify .
Step 5 - Choose individual components (Optional)
If you don't want to use the Workloads feature to customize your Visual Studio installation, or you want to add
more components than a workload installs, you can do so by installing or adding individual components from the
Individual components tab. Choose what you want, and then follow the prompts.
IMPORTANT
You can select a different drive only when you first install Visual Studio. If you've already installed it and want to change
drives, you must uninstall Visual Studio and then reinstall it.
TIP
The Community edition is for individual developers, classroom learning, academic research, and open source
development. For other uses, install Visual Studio 2017 Professional or Visual Studio 2017 Enterprise.
2. Find the installer file you downloaded and run it. The downloaded file may be displayed in your browser, or
you may find it in your Downloads folder. The installer needs Administrator privileges to run. You may see a
User Account Control dialog asking you to give permission to let the installer make changes to your
system; choose Yes . If you're having trouble, find the downloaded file in File Explorer, right-click on the
installer icon, and choose Run as Administrator from the context menu.
3. The installer presents you with a list of workloads, which are groups of related options for specific
development areas. Support for C++ is now part of optional workloads that aren't installed by default.
For C and C++, select the Desktop development with C++ workload and then choose Install .
4. When the installation completes, choose the Launch button to start Visual Studio.
The first time you run Visual Studio, you're asked to sign in with a Microsoft Account. If you don't have one,
you can create one for free. You must also choose a theme. Don't worry, you can change it later if you want
to.
It may take Visual Studio several minutes to get ready for use the first time you run it. Here's what it looks
like in a quick time-lapse:
Visual Studio starts much faster when you run it again.
5. When Visual Studio opens, check to see if the flag icon in the title bar is highlighted:
If it's highlighted, select it to open the Notifications window. If there are any updates available for Visual
Studio, we recommend you install them now. Once the installation is complete, restart Visual Studio.
Next Steps
Create a C++ project
https://docs.microsoft.com/
Create a C++ console app project
11/2/2020 • 6 minutes to read • Edit Online
The usual starting point for a C++ programmer is a "Hello, world!" application that runs on the command line.
That's what you'll create in Visual Studio in this step.
Prerequisites
Have Visual Studio with the Desktop development with C++ workload installed and running on your computer.
If it's not installed yet, see Install C++ support in Visual Studio.
2. In the Configure your new project dialog, enter HelloWorld in the Project name edit box. Choose
Create to create the project.
Visual Studio creates a new project. It's ready for you to add and edit your source code. By default, the
Console App template fills in your source code with a "Hello World" app:
When the code looks like this in the editor, you're ready to go on to the next step and build your app.
I ran into a problem.
1. In Visual Studio, open the File menu and choose New > Project to open the New Project dialog.
2. In the New Project dialog, select Installed > Visual C++ if it isn't selected already, and then choose the
Empty Project template. In the Name field, enter HelloWorld. Choose OK to create the project.
Visual Studio creates a new, empty project. It's ready for you to specialize for the kind of app you want to create
and to add your source code files. You'll do that next.
I ran into a problem.
Visual Studio now knows to build your project to run in a console window. Next, you'll add a source code file and
enter the code for your app.
I ran into a problem.
#include <iostream>
int main()
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
When the code looks like this in the editor, you're ready to go on to the next step and build your app.
I ran into a problem.
Next Steps
Build and run a C++ project
Troubleshooting guide
Come here for solutions to common issues when you create your first C++ project.
Create your app project: issues
The New Project dialog should show a Console App template that has C++ , Windows , and Console tags. If
you don't see it, there are two possible causes. It might be filtered out of the list, or it might not be installed. First,
check the filter dropdowns at the top of the list of templates. Set them to C++ , Windows , and Console . The C++
Console App template should appear; otherwise, the Desktop development with C++ workload isn't
installed.
To install Desktop development with C++ , you can run the installer right from the New Project dialog.
Choose the Install more tools and features link at the bottom of the template list to start the installer. If the
User Account Control dialog requests permissions, choose Yes . In the installer, make sure the Desktop
development with C++ workload is checked. Then choose Modify to update your Visual Studio installation.
If another project with the same name already exists, choose another name for your project. Or, delete the existing
project and try again. To delete an existing project, delete the solution folder (the folder that contains the
helloworld.sln file) in File Explorer.
Go back.
If the New Project dialog doesn't show a Visual C++ entry under Installed , your copy of Visual Studio probably
doesn't have the Desktop development with C++ workload installed. You can run the installer right from the
New Project dialog. Choose the Open Visual Studio Installer link to start the installer again. If the User
Account Control dialog requests permissions, choose Yes . Update the installer if necessary. In the installer, make
sure the Desktop development with C++ workload is checked, and choose OK to update your Visual Studio
installation.
If another project with the same name already exists, choose another name for your project. Or, delete the existing
project and try again. To delete an existing project, delete the solution folder (the folder that contains the
helloworld.sln file) in File Explorer.
Go back.
Make your project a console app: issues
If you don't see Linker listed under Configuration Proper ties , choose Cancel to close the Proper ty Pages
dialog. Make sure that the HelloWorld project is selected in Solution Explorer before you try again. Don't select
the HelloWorld solution, or another item, in Solution Explorer .
The dropdown control doesn't appear in the SubSystem property edit box until you select the property. Click in
the edit box to select it. Or, you can press Tab to cycle through the dialog controls until SubSystem is highlighted.
Choose the dropdown control or press Alt+Down to open it.
Go back
Add a source code file: issues
It's okay if you give the source code file a different name. However, don't add more than one file that contains the
same code to your project.
If you added the wrong file type to your project, such as a header file, delete it and try again. To delete the file,
select it in Solution Explorer . Then press the Delete key.
Go back.
Add code to the source file: issues
If you accidentally closed the source code file editor window, you can easily open it again. To open it, double-click
on HelloWorld.cpp in the Solution Explorer window.
If red squiggles appear under anything in the source code editor, check that your code matches the example in
spelling, punctuation, and case. Case is significant in C++ code.
Go back.
https://docs.microsoft.com/
Build and run a C++ console app project
4/21/2020 • 3 minutes to read • Edit Online
You've created a C++ console app project and entered your code. Now you can build and run it within Visual
Studio. Then, run it as a stand-alone app from the command line.
Prerequisites
Have Visual Studio with the Desktop development with C++ workload installed and running on your
computer. If it's not installed yet, follow the steps in Install C++ support in Visual Studio.
Create a "Hello, World!" project and enter its source code. If you haven't done this step yet, follow the steps
in Create a C++ console app project.
If Visual Studio looks like this, you're ready to build and run your app:
A console window opens and then runs your app. When you start a console app in Visual Studio, it runs
your code, then prints "Press any key to continue . . ." to give you a chance to see the output.
Congratulations! You've created your first "Hello, world!" console app in Visual Studio! Press a key to dismiss the
console window and return to Visual Studio.
I ran into a problem.
Next Steps
Once you've built and run this simple app, you're ready for more complex projects. For more information, see
Using the Visual Studio IDE for C++ Desktop Development. It has more detailed walkthroughs that explore the
capabilities of Microsoft C++ in Visual Studio.
Troubleshooting guide
Come here for solutions to common issues when you create your first C++ project.
Build and run your code in Visual Studio: issues
If red squiggles appear under anything in the source code editor, the build may have errors or warnings. Check that
your code matches the example in spelling, punctuation, and case.
Go back.
Run your code in a command window: issues
If the path shown in File Explorer ends in \HelloWorld\HelloWorld, you've opened the HelloWorld project instead of
the HelloWorld solution. You'll be confused by a Debug folder that doesn't contain your app. Navigate up a level in
File Explorer to get to the solution folder, the first HelloWorld in the path. This folder also contains a Debug folder,
and you'll find your app there.
You can also navigate to the solution Debug folder at the command line to run your app. Your app won't run from
other directories without specifying the path to the app. However, you can copy your app to another directory and
run it from there. It's also possible to copy it to a directory specified by your PATH environment variable, then run it
from anywhere.
If you don't see Copy as path in the shortcut menu, dismiss the menu, and then hold down the Shift key while
you open it again. This command is just for convenience. You can also copy the path to the folder from the File
Explorer search bar, and paste it into the Run dialog, and then enter the name of your executable at the end. It's just
a little more typing, but it has the same result.
Go back.
https://docs.microsoft.com/
Create a console calculator in C++
11/2/2020 • 37 minutes to read • Edit Online
The usual starting point for a C++ programmer is a "Hello, world!" application that runs on the command line.
That's what you'll create first in Visual Studio in this article, and then we'll move on to something more challenging:
a calculator app.
Prerequisites
Have Visual Studio with the Desktop development with C++ workload installed and running on your
computer. If it's not installed yet, see Install C++ support in Visual Studio.
Otherwise, on the menubar in Visual Studio, choose File > New > Project . The Create a new project
window opens.
2. In the list of project templates, choose Console App , then choose Next .
IMPORTANT
Make sure you choose the C++ version of the Console App template. It has the C++ , Windows , and Console
tags, and the icon has "++" in the corner.
3. In the Configure your new project dialog box, select the Project name edit box, name your new project
CalculatorTutorial, then choose Create .
An empty C++ Windows console application gets created. Console applications use a Windows console
window to display output and accept user input. In Visual Studio, an editor window opens and shows the
generated code:
// CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends
there.
//
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
}
2. To run the code, on the menu bar, choose Debug , Star t without debugging .
A console window opens and then runs your app. When you start a console app in Visual Studio, it runs your
code, then prints "Press any key to close this window . . ." to give you a chance to see the output.
Congratulations! You've created your first "Hello, world!" console app in Visual Studio!
3. Press a key to dismiss the console window and return to Visual Studio.
You now have the tools to build and run your app after every change, to verify that the code still works as you
expect. Later, we'll show you how to debug it if it doesn't.
// CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends
there.
//
#include <iostream>
int main()
{
cout << "Calculator Console Application" << endl << endl;
cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b"
<< endl;
return 0;
}
2. To save the file, enter Ctrl+S , or choose the Save icon near the top of the IDE, the floppy disk icon in the
toolbar under the menu bar.
3. To run the application, press Ctrl+F5 or go to the Debug menu and choose Star t Without Debugging .
You should see a console window appear that displays the text specified in the code.
4. Close the console window when you're done.
You should now have three tabs open in the editor: CalculatorTutorial.cpp, Calculator.h, and Calculator.cpp. If
you accidentally close one of them, you can reopen it by double-clicking it in the Solution Explorer
window.
2. In Calculator.h , remove the Calculator(); and ~Calculator(); lines that were generated, since you won't
need them here. Next, add the following line of code so the file now looks like this:
#pragma once
class Calculator
{
public:
double Calculate(double x, char oper, double y);
};
3. You'll see a green squiggle appear under Calculate . It's because we haven't defined the Calculate function
in the .cpp file. Hover over the word, click the lightbulb (in this case, a screwdriver) that pops up, and choose
Create definition of 'Calculate' in Calculator.cpp .
A pop-up appears that gives you a peek of the code change that was made in the other file. The code was
added to Calculator.cpp.
Currently, it just returns 0.0. Let's change that. Press Esc to close the pop-up.
4. Switch to the Calculator.cpp file in the editor window. Remove the Calculator() and ~Calculator() sections
(as you did in the .h file) and add the following code to Calculate() :
#include "Calculator.h"
If you build and run the code again at this point, it will still exit after asking which operation to perform. Next, you'll
modify the main function to do some calculations.
To call the Calculator class member functions
1. Now let's update the main function in CalculatorTutorial.cpp:
// CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends
there.
//
#include <iostream>
#include "Calculator.h"
int main()
{
double x = 0.0;
double y = 0.0;
double result = 0.0;
char oper = '+';
Calculator c;
while (true)
{
cin >> x >> oper >> y;
result = c.Calculate(x, oper, y);
cout << "Result is: " << result << endl;
}
return 0;
}
You can also just hover over variables in the code itself to see their current values where the execution is currently
paused. Make sure the editor window is in focus by clicking on it first.
To continue debugging
1. The yellow line on the left shows the current point of execution. The current line calls Calculate , so press
F11 to Step Into the function. You'll find yourself in the body of the Calculate function. Be careful with
Step Into ; if you do it too much, you may waste a lot of time. It goes into any code you use on the line you
are on, including standard library functions.
2. Now that the point of execution is at the start of the Calculate function, press F10 to move to the next line
in the program's execution. F10 is also known as Step Over . You can use Step Over to move from line to
line, without delving into the details of what is occurring in each part of the line. In general you should use
Step Over instead of Step Into , unless you want to dive more deeply into code that is being called from
elsewhere (as you did to reach the body of Calculate ).
3. Continue using F10 to Step Over each line until you get back to the main() function in the other file, and
stop on the cout line.
It looks like the program is doing what is expected: it takes the first number, and divides it by the second. On
the cout line, hover over the result variable or take a look at result in the Autos window. You'll see its
value is listed as "inf", which doesn't look right, so let's fix it. The cout line just outputs whatever value is
stored in result , so when you step one more line forward using F10 , the console window displays:
This result happens because division by zero is undefined, so the program doesn't have a numerical answer
to the requested operation.
To fix the "divide by zero" error
Let's handle division by zero more gracefully, so a user can understand the problem.
1. Make the following changes in CalculatorTutorial.cpp. (You can leave the program running as you edit,
thanks to a debugger feature called Edit and Continue ):
// CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends
there.
//
#include <iostream>
#include "Calculator.h"
int main()
{
double x = 0.0;
double y = 0.0;
double result = 0.0;
char oper = '+';
Calculator c;
while (true)
{
cin >> x >> oper >> y;
if (oper == '/' && y == 0)
{
cout << "Division by 0 exception" << endl;
continue;
}
else
{
result = c.Calculate(x, oper, y);
}
cout << "Result is: " << result << endl;
}
return 0;
}
2. Now press F5 once. Program execution continues all the way until it has to pause to ask for user input. Enter
10 / 0 again. Now, a more helpful message is printed. The user is asked for more input, and the program
continues executing normally.
NOTE
When you edit code while in debugging mode, there is a risk of code becoming stale. This happens when the
debugger is still running your old code, and has not yet updated it with your changes. The debugger pops up a
dialog to inform you when this happens. Sometimes, you may need to press F5 to refresh the code being executed.
In particular, if you make a change inside a function while the point of execution is inside that function, you'll need to
step out of the function, then back into it again to get the updated code. If that doesn't work for some reason and
you see an error message, you can stop debugging by clicking on the red square in the toolbar under the menus at
the top of the IDE, then start debugging again by entering F5 or by choosing the green "play" arrow beside the stop
button on the toolbar.
Next steps
Learn more about Visual Studio for C++
The usual starting point for a C++ programmer is a "Hello, world!" application that runs on the command line.
That's what you'll create in Visual Studio in this article, and then we'll move on to something more challenging: a
calculator app.
Prerequisites
Have Visual Studio with the Desktop development with C++ workload installed and running on your
computer. If it's not installed yet, see Install C++ support in Visual Studio.
An empty C++ Windows console application gets created. Console applications use a Windows console
window to display output and accept user input. In Visual Studio, an editor window opens and shows the
generated code:
// CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends
there.
//
#include "pch.h"
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
}
2. To run the code, on the menu bar, choose Debug , Star t without debugging .
A console window opens and then runs your app. When you start a console app in Visual Studio, it runs your
code, then prints "Press any key to continue . . ." to give you a chance to see the output. Congratulations!
You've created your first "Hello, world!" console app in Visual Studio!
3. Press a key to dismiss the console window and return to Visual Studio.
You now have the tools to build and run your app after every change, to verify that the code still works as you
expect. Later, we'll show you how to debug it if it doesn't.
Edit the code
Now let's turn the code in this template into a calculator app.
1. In the CalculatorTutorial.cpp file, edit the code to match this example:
// CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends
there.
//
#include "pch.h"
#include <iostream>
int main()
{
cout << "Calculator Console Application" << endl << endl;
cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b"
<< endl;
return 0;
}
You should now have three tabs open in the editor: CalculatorTutorial.cpp, Calculator.h, and Calculator.cpp. If
you accidentally close one of them, you can reopen it by double-clicking it in the Solution Explorer
window.
2. In Calculator.h , remove the Calculator(); and ~Calculator(); lines that were generated, since you won't
need them here. Next, add the following line of code so the file now looks like this:
#pragma once
class Calculator
{
public:
double Calculate(double x, char oper, double y);
};
3. You'll see a green squiggle appear under Calculate . It's because we haven't defined the Calculate function
in the .cpp file. Hover over the word, click the lightbulb that pops up, and choose Create definition of
'Calculate' in Calculator.cpp . A pop-up appears that gives you a peek of the code change that was made
in the other file. The code was added to Calculator.cpp.
Currently, it just returns 0.0. Let's change that. Press Esc to close the pop-up.
4. Switch to the Calculator.cpp file in the editor window. Remove the Calculator() and ~Calculator() sections
(as you did in the .h file) and add the following code to Calculate() :
#include "pch.h"
#include "Calculator.h"
If you build and run the code again at this point, it will still exit after asking which operation to perform. Next, you'll
modify the main function to do some calculations.
To call the Calculator class member functions
1. Now let's update the main function in CalculatorTutorial.cpp:
// CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends
there.
//
#include "pch.h"
#include <iostream>
#include "Calculator.h"
int main()
{
double x = 0.0;
double y = 0.0;
double result = 0.0;
char oper = '+';
Calculator c;
while (true)
{
cin >> x >> oper >> y;
result = c.Calculate(x, oper, y);
cout << "Result is: " << result << endl;
}
return 0;
}
Now when we debug the program, it always pauses execution at that line. We already have a rough idea that
the program works for simple cases. Since we don't want to pause execution every time, let's make the
breakpoint conditional.
2. Right-click the red dot that represents the breakpoint, and choose Conditions . In the edit box for the
condition, enter (y == 0) && (oper == '/') . Choose the Close button when you're done. The condition is
saved automatically.
You can also just hover over variables in the code itself to see their current values where the execution is currently
paused. Make sure the editor window is in focus by clicking on it first.
To continue debugging
1. The yellow line on the left shows the current point of execution. The current line calls Calculate , so press
F11 to Step Into the function. You'll find yourself in the body of the Calculate function. Be careful with
Step Into ; if you do it too much, you may waste a lot of time. It goes into any code you use on the line you
are on, including standard library functions.
2. Now that the point of execution is at the start of the Calculate function, press F10 to move to the next line
in the program's execution. F10 is also known as Step Over . You can use Step Over to move from line to
line, without delving into the details of what is occurring in each part of the line. In general you should use
Step Over instead of Step Into , unless you want to dive more deeply into code that is being called from
elsewhere (as you did to reach the body of Calculate ).
3. Continue using F10 to Step Over each line until you get back to the main() function in the other file, and
stop on the cout line.
It looks like the program is doing what is expected: it takes the first number, and divides it by the second. On
the cout line, hover over the result variable or take a look at result in the Autos window. You'll see its
value is listed as "inf", which doesn't look right, so let's fix it. The cout line just outputs whatever value is
stored in result , so when you step one more line forward using F10 , the console window displays:
This result happens because division by zero is undefined, so the program doesn't have a numerical answer
to the requested operation.
To fix the "divide by zero" error
Let's handle division by zero more gracefully, so a user can understand the problem.
1. Make the following changes in CalculatorTutorial.cpp. (You can leave the program running as you edit,
thanks to a debugger feature called Edit and Continue ):
// CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends
there.
//
#include "pch.h"
#include <iostream>
#include "Calculator.h"
int main()
{
double x = 0.0;
double y = 0.0;
double result = 0.0;
char oper = '+';
Calculator c;
while (true)
{
cin >> x >> oper >> y;
if (oper == '/' && y == 0)
{
cout << "Division by 0 exception" << endl;
continue;
}
else
{
result = c.Calculate(x, oper, y);
}
cout << "Result is: " << result << endl;
}
return 0;
}
2. Now press F5 once. Program execution continues all the way until it has to pause to ask for user input. Enter
10 / 0 again. Now, a more helpful message is printed. The user is asked for more input, and the program
continues executing normally.
NOTE
When you edit code while in debugging mode, there is a risk of code becoming stale. This happens when the
debugger is still running your old code, and has not yet updated it with your changes. The debugger pops up a
dialog to inform you when this happens. Sometimes, you may need to press F5 to refresh the code being executed.
In particular, if you make a change inside a function while the point of execution is inside that function, you'll need to
step out of the function, then back into it again to get the updated code. If that doesn't work for some reason and
you see an error message, you can stop debugging by clicking on the red square in the toolbar under the menus at
the top of the IDE, then start debugging again by entering F5 or by choosing the green "play" arrow beside the stop
button on the toolbar.
Next steps
Learn more about Visual Studio for C++
C/C++ projects and build systems in Visual Studio
11/2/2020 • 4 minutes to read • Edit Online
You can use Visual Studio to edit, compile, and build any C++ code base with full IntelliSense support without
having to convert that code into a Visual Studio project or compile with the MSVC toolset. For example, you can
edit a cross-platform CMake project in Visual Studio on a Windows machine, then compile it for Linux using g++
on a remote Linux machine.
C++ compilation
To build a C++ program means to compile source code from one or more files and then link those files into an
executable file (.exe), a dynamic-load library (.dll) or a static library (.lib).
Basic C++ compilation involves three main steps:
The C++ preprocessor transforms all the #directives and macro definitions in each source file. This creates a
translation unit.
The C++ compiler compiles each translation unit into object files (.obj), applying whatever compiler options
have been set.
The linker merges the object files into a single executable, applying the linker options that have been set.
cl /EHsc hello.cpp
Here the compiler (cl.exe) automatically invokes the C++ preprocessor and the linker to produce the final output
file. For more information, see Building on the command line.
In This Section
Visual Studio projects
How to create, configure, and build C++ projects in Visual Studio using its native build system (MSBuild).
CMake projects
How to code, build, and deploy CMake projects in Visual Studio.
Open Folder projects
How to use Visual Studio to code, build, and deploy C++ projects based on any arbitrary build system, or no build
system at all.
Release builds
How to create and troubleshoot optimized release builds for deployment to end users.
Use the MSVC toolset from the command line
Discusses how to use the C/C++ compiler and build tools directly from the command line rather than using the
Visual Studio IDE.
Building DLLs in Visual Studio
How to create, debug, and deploy C/C++ DLLs (shared libraries) in Visual Studio.
Walkthrough: Creating and Using a Static Library
How to create a .lib binary file.
Building C/C++ Isolated Applications and Side-by-side Assemblies
Describes the deployment model for Windows Desktop applications, based on the idea of isolated applications and
side-by-side assemblies.
Configure C++ projects for 64-bit, x64 targets
How to target 64-bit x64 hardware with the MSVC build tools.
Configure C++ projects for ARM processors
How to use the MSVC build tools to target ARM hardware.
Optimizing Your Code
How to optimize your code in various ways including program guided optimizations.
Configuring Programs for Windows XP
How to target Windows XP with the MSVC build tools.
C/C++ Building Reference
Provides links to reference articles about program building in C++, compiler and linker options, and various build
tools.
Read and understand C++ code in Visual Studio
11/2/2020 • 3 minutes to read • Edit Online
The C++ code editor and Visual Studio IDE provide many coding aids. Some are unique to C++, and some are
essentially the same for all Visual Studio languages. For more information about the shared features, see Writing
Code in the Code and Text Editor.
Colorization
Visual Studio colorizes syntax elements to differentiate between types of symbols such as language keywords, type
names, variable names, function parameters, string literals, and so on.
You can customize the colors by typing "Fonts" in Quick Launch , and then choosing Fonts and Colors . In the
Fonts and Colors dialog scroll down to the C/C++ options and then choose a custom font and/or color.
Outlining
Right-click anywhere in a source code file and choose Outlining to collapse or expand code blocks and/or custom
regions to make it easier to browse only the code you are interested in. For more information, see Outlining.
When you place your cursor in front of a curly brace, '{' or '}', the editor highlights its matching counterpart.
Other outlining options are located under Edit > Outlining in the main menu.
Line numbers
You can add line numbers to your project by going to Tools > Options > Text Editor > All Languages >
General or by searching for "line num" with Quick Launch (Ctrl + Q) . Line numbers can be set for all languages
or for specific languages only, including C++.
Scrollbar Map Mode enables you to quickly scroll and browse through a code file without leaving your current
location. You can click anywhere on the code map to go directly to that location.
To turn on Map Mode , type "map" in the Quick Launch search box in the main toolbar and choose Use scroll
map mode . For more information, see How to: Track your code by customizing the scrollbar.
When Map Mode is off, the scroll bar still highlights the changes you have made in the file. Green indicates saved
changes and yellow indicates unsaved changes.
The Quick Info tooltip has a Search Online link. Go to Tools > Options > Text Editor > C++ > View to specify
the search provider.
If there is an error in your code, you can hover over it and Quick Info will display the error message. You can also
find the error message in the Error List window.
If there is an error in your code, you can hover over it and Quick Info will display the error message. You can also
find the error message in the Error List window.
When you call a function, Parameter Info shows the types of parameters and the order in which they are
expected.
Peek Definition
Hover over a variable or function declaration, right-click, then choose Peek Definition to see an inline view of its
definition without navigating away from your current location. For more information, see Peek Definition (Alt+F12).
F1 Help
Place the cursor on or just after any type, keyword or function and press F1 to go directly to the relevant reference
topic on docs.microsoft.com. F1 also works on items in the error list, and in many dialog boxes.
Class View
Class View displays a searchable set of trees of all code symbols and their scope and parent/child hierarchies,
organized on a per-project basis. You can configure what Class View displays from Class View Settings (click
the gear box icon at the top of the window).
Generate graph of include files
Right click on a code file in your project and choose Generate graph of include files to see a graph of which
files are included by other files.
There are several broad categories of Windows applications that you can create with C++. Each has its own
programming model and set of Windows-specific libraries, but the C++ standard library and third-party C++
libraries can be used in any of them.
This section discusses how to use Visual Studio and the MFC/ATL wrapper libraries to create Windows programs.
For documentation on the Windows platform itself, see Windows documentation.
COM Components
The Component Object Model (COM) is a specification that enables programs written in different languages to
communicate with one another. Many Windows components are implemented as COM objects and follow standard
COM rules for object creation, interface discovery, and object destruction. Using COM objects from C++ desktop
applications is relatively straightforward, but writing your own COM object is more advanced. The Active Template
Library (ATL) provides macros and helper functions that simplify COM development. For more information, see ATL
COM desktop components.
Desktop Bridge
In Windows 10, you can package your existing desktop application or COM object as a UWP app, and add UWP
features such as touch, or call APIs from the modern Windows API set. You can also add a UWP app to a desktop
solution in Visual Studio, and package them together in a single package and use Windows APIs to communicate
between them.
Visual Studio 2017 version 15.4 and later lets you create a Windows Application Package Project to greatly simplify
the work of packaging your existing desktop application. A few restrictions apply to the registry calls or APIs your
desktop application can use. However, in many cases you can create alternate code paths to achieve similar
functionality while running in an app package. For more information, see Desktop Bridge.
Games
DirectX games can run on the PC or Xbox. For more information, see DirectX Graphics and Gaming.
Windows services
A Windows service is a program that can run in the background with little or no user interaction. These programs
are called daemons on UNIX systems. For more information, see Services.
Development Tools
Visual Studio includes a powerful debugger for native code, static analysis tools, graphics debugging tools, a full-
featured code editor, support for unit tests, and many other tools and utilities. For more information, see Get
started developing with Visual Studio, and Overview of C++ development in Visual Studio.
In this section
T IT L E DESC RIP T IO N
Walkthrough: Creating Windows Desktop Applications (C++) Create a native Windows desktop application.
Windows Desktop Wizard Use the wizard to create new Windows projects.
Active Template Library (ATL) Use the ATL library to create COM components in C++.
Microsoft Foundation Classes (MFC) Use MFC to create large or small Windows applications with
dialogs and controls
ATL and MFC Shared Classes Use classes such as CString that are shared in ATL and MFC.
T IT L E DESC RIP T IO N
How to: Use the Windows 10 SDK in a Windows Desktop Windows SDK
Application
Working with Resource Files How to add images, icons, string tables, and other resources
to a desktop application.
Resources for Creating a Game Using DirectX (C++) Links to content for creating games in C++.
How to: Use the Windows 10 SDK in a Windows Desktop Contains steps for setting up your project to build using the
Application Windows 10 SDK.
Related Articles
T IT L E DESC RIP T IO N
C++ in Visual Studio Parent topic for Visual C++ developer content.
.NET Development with C++/CLI Create wrappers for native C++ libraries that enable it to
communication with .NET applications and components.
Component Extensions for .NET and UWP Reference for syntax elements shared by C++/CX and
C++/CLI.
Universal Windows Apps (C++) Write UWP applications using C++/CX or Windows Runtime
Template Library (WRL).
C++ Attributes for COM and .NET Non-standard attributes for Windows-only programming
using .NET or COM.
Universal Windows Apps (C++)
12/18/2020 • 2 minutes to read • Edit Online
The Universal Windows Platform (UWP) is the modern programming interface for Windows. With UWP you write
an application or component once and deploy it on any Windows 10 device. You can write a component in C++
and applications written in any other UWP-compatible language can use it.
Most of the UWP documentation is in the Windows content tree at Universal Windows Platform documentation.
There you will find beginning tutorials as well as reference documentation.
For new UWP apps and components, we recommend that you use C++/WinRT, a new standard C++17 language
projection for Windows Runtime APIs. C++/WinRT is available in the Windows 10 SDK from version 1803 onward.
C++/WinRT is implemented entirely in header files, and is designed to provide you with first-class access to the
modern Windows API. Unlike the C++/CX implementation, C++/WinRT doesn't use non-standard syntax or
Microsoft language extensions, and it takes full advantage of the C++ compiler to create highly-optimized output.
For more information, see Introduction to C++/WinRT.
You can use the Desktop Bridge app converter to package your existing desktop application for deployment
through the Microsoft Store. For more information, see Using Visual C++ Runtime in Centennial project and
Desktop Bridge.
UWP Apps that Use the Windows Runtime C++ Template Library (WRL)
The Windows Runtime C++ Template Library provides the low-level COM interfaces by which ISO C++ code can
access the Windows Runtime in an exception-free environment. In most cases, we recommend that you use
C++/WinRT or C++/CX instead of the Windows Runtime C++ Template Library for UWP app development. For
information about the Windows Runtime C++ Template Library, see Windows Runtime C++ Template Library
(WRL).
See also
C++ in Visual Studio
Overview of Windows Programming in C++
Game Development with C++
12/18/2020 • 2 minutes to read • Edit Online
When you create a Windows 10 game, you have the opportunity to reach millions of players worldwide across
phone, PC, and Xbox One. With Xbox on Windows, Xbox Live, cross-device multiplayer, an amazing gaming
community, and powerful new features like the Universal Windows Platform (UWP) and DirectX 12, Windows 10
games thrill players of all ages and genres. The new Universal Windows Platform (UWP) delivers compatibility for
your game across Windows 10 devices with a common API for phone, PC, and Xbox One, along with tools and
options to tailor your game to each device experience.
Game development is documented on the Windows Dev Center.
.NET programming with C++/CLI
12/18/2020 • 2 minutes to read • Edit Online
By default, CLR projects created with Visual Studio 2015 target .NET Framework 4.5.2. You can target .NET
Framework 4.6 when you create a new project. In the New Project dialog, change the target framework in the
dropdown at the top middle of the dialog. To change the target framework for an existing project, close the
project, edit the project file ( .vcxproj ), and change the value of the Target Framework Version to 4.6. The changes
take effect the next time you open the project.
In Visual Studio 2017, the default target .NET Framework is 4.6.1. The Framework version selector is at the bottom
of the New Project dialog.
In this section
C++/CLI tasks
Native and .NET interoperability
Pure and verifiable code (C++/CLI)
Regular expressions (C++/CLI)
File handling and I/O (C++/CLI)
Graphics operations (C++/CLI)
Windows operations (C++/CLI)
Data access using ADO.NET (C++/CLI)
Interoperability with other .NET languages (C++/CLI)
Serialization (C++/CLI)
Managed types (C++/CLI)
Reflection (C++/CLI)
Strong Name assemblies (assembly signing) (C++/CLI)
Debug class (C++/CLI)
STL/CLR library reference
C++ support library
Exceptions in C++/CLI
Boxing (C++/CLI)
See also
Native and .NET interoperability
Cloud and Web Programming in Visual C++
12/18/2020 • 2 minutes to read • Edit Online
In C++, you have several options for connecting to the web and the cloud.
See also
C++ in Visual Studio
Microsoft Azure C and C++ Developer Center
Networks and web services (UWP)
Microsoft C++ porting and upgrading guide
11/2/2020 • 3 minutes to read • Edit Online
This article provides a guide for upgrading Microsoft C++ code to the latest version of Visual Studio. For projects
created in Visual Studio 2010 through 2015, just open the project in Visual Studio 2019. You can upgrade a Visual
Studio 2008 or earlier project in two steps. Use Visual Studio 2010 to convert the project to MSBuild format first.
Then open the project in Visual Studio 2019. For complete instructions, see Upgrading C++ projects from earlier
versions of Visual Studio.
The toolsets in Visual Studio 2015, Visual Studio 2017, and Visual Studio 2019 are binary-compatible. Now you can
upgrade to a more recent version of the compiler without having to upgrade your library dependencies. For more
information, see C++ binary compatibility 2015-2019.
When upgrading projects that use open-source libraries or are meant to run on multiple platforms, we
recommended migrating to a CMake-based project. For more information, see CMake projects in Visual Studio
In this section
T IT L E DESC RIP T IO N
Upgrading C++ projects from earlier versions of Visual Studio How to upgrade your code base to Visual Studio 2019 and
v142 of the compiler.
IDE tools for upgrading C++ code Useful IDE features that help in the upgrade process.
C++ binary compatibility 2015-2019 Consume v140 and v141 libraries as-is from v142 projects.
Use native multi-targeting in Visual Studio to build old Use Visual Studio 2019 with older compilers and libraries.
projects
Visual C++ change history 2003 - 2015 A list of all the changes in the Microsoft C++ libraries and
build tools from Visual Studio 2003 through 2015 that might
require changes in your code.
Visual C++ What's New 2003 through 2015 All the "what's new" information for Microsoft C++ from
Visual Studio 2003 through Visual Studio 2015.
Porting and Upgrading: Examples and Case Studies For this section, we ported and upgrades several samples and
applications and discussed the experiences and results. These
articles give you a sense of what's involved in the porting and
upgrading process. Throughout the process, we discuss tips
and tricks for upgrading and show how specific errors were
fixed.
Porting to the Universal Windows Platform Contains information about porting code to Windows 10
Introduction to Visual C++ for UNIX Users Provides information for UNIX users who are new to Visual
C++ and want to become productive with it.
Running Linux programs on Windows Discusses options for migrating UNIX applications to
Windows.
See also
C++ in Visual Studio
What's New for The C++ compiler in Visual Studio
C++ conformance improvements in Visual Studio
Security Best Practices for C++
12/18/2020 • 3 minutes to read • Edit Online
This article contains information about security tools and practices. Using them does not make applications
immune from attack, but it makes successful attacks less likely.
Security-Enhanced CRT
The C Runtime Library (CRT) has been augmented to include secure versions of functions that pose security risks—
for example, the unchecked strcpy string copy function. Because the older, nonsecure versions of these functions
are deprecated, they cause compile-time warnings. We encourage you to use the secure versions of these CRT
functions instead of suppressing the compilation warnings. For more information, see Security Features in the CRT.
SafeInt Library
SafeInt Library helps prevent integer overflows and other exploitable errors that might occur when the application
performs mathematical operations. The SafeInt library includes the SafeInt Class, the SafeIntException Class, and
several SafeInt Functions.
The SafeInt class protects against integer overflow and divide-by-zero exploits. You can use it to handle
comparisons between values of different types. It provides two error handling policies. The default policy is for the
SafeInt class to throw a SafeIntException class exception to report why a mathematical operation cannot be
completed. The second policy is for the SafeInt class to stop program execution. You can also define a custom
policy.
Each SafeInt function protects one mathematical operation from an exploitable error. You can use two different
kinds of parameters without converting them to the same type. To protect multiple mathematical operations, use
the SafeInt class.
Checked Iterators
A checked iterator enforces container boundaries. By default, when a checked iterator is out of bounds, it generates
an exception and ends program execution. A checked iterator provides other levels of response that depend on
values that are assigned to preprocessor defines such as _SECURE_SCL_THROWS and _ITERATOR_DEBUG_LEVEL . For
example, at _ITERATOR_DEBUG_LEVEL=2 , a checked iterator provides comprehensive correctness checks in debug
mode, which are made available by using asserts. For more information, see Checked Iterators and
_ITERATOR_DEBUG_LEVEL .
This topic explains how configuring Windows user accounts as a member of the Users Group (as opposed to the
Administrators Group) increases security by reducing the chances of being infected with malicious code.
Security Risks
Running as an administrator makes your system vulnerable to several kinds of security attack, such as "Trojan
horse" and "buffer overrun." Merely visiting an Internet site as an administrator can be damaging to the system, as
malicious code that is downloaded from an Internet site may attack your computer. If successful, it inherits your
administrator permissions and can then perform actions such as deleting all your files, reformatting your hard
drive, and creating a new user accounts with administrative access.
Debugging
You can debug any applications that you launch within Visual Studio (native and unmanaged) as a non-
administrator by becoming part of the Debugging Group. This includes the ability to attach to a running application
using the Attach to Process command. However, it is necessary to be part of the Administrator Group in order to
debug native or managed applications that were launched by a different user.
See also
Security Best Practices
How User Account Control (UAC) Affects Your
Application
12/18/2020 • 2 minutes to read • Edit Online
User Account Control (UAC) is a feature of Windows Vista in which user accounts have limited privileges. You can
find detailed information about UAC at these sites:
Developer Best Practices and Guidelines for Applications in a Least Privileged Environment
This article contains guidance for developers to assist with identifying and mitigating speculative execution side
channel hardware vulnerabilities in C++ software. These vulnerabilities can disclose sensitive information across
trust boundaries and can affect software that runs on processors that support speculative, out-of-order execution
of instructions. This class of vulnerabilities was first described in January, 2018 and additional background and
guidance can be found in Microsoft's security advisory.
The guidance provided by this article is related to the classes of vulnerabilities represented by:
1. CVE-2017-5753, also known as Spectre variant 1. This hardware vulnerability class is related to side
channels that can arise due to speculative execution that occurs as a result of a conditional branch
misprediction. The Microsoft C++ compiler in Visual Studio 2017 (starting with version 15.5.5) includes
support for the /Qspectre switch which provides a compile-time mitigation for a limited set of potentially
vulnerable coding patterns related to CVE-2017-5753. The /Qspectre switch is also available in Visual
Studio 2015 Update 3 through KB 4338871. The documentation for the /Qspectre flag provides more
information on its effects and usage.
2. CVE-2018-3639, also known as Speculative Store Bypass (SSB). This hardware vulnerability class is related
to side channels that can arise due to speculative execution of a load ahead of a dependent store as a result
of a memory access misprediction.
An accessible introduction to speculative execution side channel vulnerabilities can be found in the presentation
titled The Case of Spectre and Meltdown by one of the research teams that discovered these issues.
unsigned char ReadByte(unsigned char *buffer, unsigned int buffer_size, unsigned int untrusted_index) {
if (untrusted_index < buffer_size) {
unsigned char value = buffer[untrusted_index];
return shared_buffer[value * 4096];
}
}
In this example, ReadByte is supplied a buffer, a buffer size, and an index into that buffer. The index parameter, as
specified by untrusted_index , is supplied by a less privileged context, such as a non-administrative process. If
untrusted_index is less than buffer_size , then the character at that index is read from buffer and used to index
into a shared region of memory referred to by shared_buffer .
From an architectural perspective, this code sequence is perfectly safe as it is guaranteed that untrusted_index will
always be less than buffer_size . However, in the presence of speculative execution, it is possible that the CPU will
mispredict the conditional branch and execute the body of the if statement even when untrusted_index is greater
than or equal to buffer_size . As a consequence of this, the CPU may speculatively read a byte from beyond the
bounds of buffer (which could be a secret) and could then use that byte value to compute the address of a
subsequent load through shared_buffer .
While the CPU will eventually detect this misprediction, residual side effects may be left in the CPU cache that
reveal information about the byte value that was read out of bounds from buffer . These side effects can be
detected by a less privileged context running on the system by probing how quickly each cache line in
shared_buffer is accessed. The steps that can be taken to accomplish this are:
1. Invoke ReadByte multiple times with untrusted_index being less than buffer_size . The attacking
context can cause the victim context to invoke ReadByte (e.g. via RPC) such that the branch predictor is
trained to be not-taken as untrusted_index is less than buffer_size .
2. Flush all cache lines in shared_buffer . The attacking context must flush all of the cache lines in the
shared region of memory referred to by shared_buffer . Since the memory region is shared, this is
straightforward and can be accomplished using intrinsics such as _mm_clflush .
3. Invoke ReadByte with untrusted_index being greater than buffer_size . The attacking context causes
the victim context to invoke ReadByte such that it incorrectly predicts that the branch will not be taken. This
causes the processor to speculatively execute the body of the if block with untrusted_index being greater
than buffer_size , thus leading to an out-of-bounds read of buffer . Consequently, shared_buffer is
indexed using a potentially secret value that was read out-of-bounds, thus causing the respective cache line
to be loaded by the CPU.
4. Read each cache line in shared_buffer to see which is accessed most quickly . The attacking context
can read each cache line in shared_buffer and detect the cache line that loads significantly faster than the
others. This is the cache line that is likely to have been brought in by step 3. Since there is a 1:1 relationship
between byte value and cache line in this example, this allows the attacker to infer the actual value of the
byte that was read out-of-bounds.
The above steps provide an example of using a technique known as FLUSH+RELOAD in conjunction with exploiting
an instance of CVE-2017-5753.
Kernel boundary A kernel-mode device driver that receives untrusted data from
a non-administrative user mode process may be at risk.
Applications that have attack surface exposed to any of the above trust boundaries should review code on the
attack surface to identify and mitigate possible instances of speculative execution side channel vulnerabilities. It
should be noted that trust boundaries exposed to remote attack surfaces, such as remote network protocols, have
not been demonstrated to be at risk to speculative execution side channel vulnerabilities.
unsigned char ReadByte(unsigned char *buffer, unsigned int buffer_size, unsigned int untrusted_index) {
if (untrusted_index < buffer_size) {
// SPECULATION BARRIER
unsigned char value = buffer[untrusted_index];
return shared_buffer[value * 4096];
}
}
Similarly, an array out-of-bounds load may occur in conjunction with a loop that exceeds its terminating condition
due to a misprediction. In this example, the conditional branch associated with the x < buffer_size expression
may mispredict and speculatively execute the body of the for loop when x is greater than or equal to
buffer_size , thus resulting in a speculative out-of-bounds load.
#define MAX_MESSAGE_ID 16
void DispatchMessage(unsigned int untrusted_message_id, unsigned char *buffer, unsigned int buffer_size) {
if (untrusted_message_id < MAX_MESSAGE_ID) {
// SPECULATION BARRIER
DispatchTable[untrusted_message_id](buffer, buffer_size);
}
}
As with the case of an array out-of-bounds load feeding another load, this condition may also arise in conjunction
with a loop that exceeds its terminating condition due to a misprediction.
Array out-of-bounds store feeding an indirect branch
While the previous example showed how a speculative out-of-bounds load can influence an indirect branch target,
it is also possible for an out-of-bounds store to modify an indirect branch target, such as a function pointer or a
return address. This can potentially lead to speculative execution from an attacker-specified address.
In this example, an untrusted index is passed through the untrusted_index parameter. If untrusted_index is less
than the element count of the pointers array (256 elements), then the provided pointer value in ptr is written to
the pointers array. This code is safe architecturally, but if the CPU mispredicts the conditional branch, it could
result in ptr being speculatively written beyond the bounds of the stack-allocated pointers array. This could lead
to speculative corruption of the return address for WriteSlot . If an attacker can control the value of ptr , they may
be able to cause speculative execution from an arbitrary address when WriteSlot returns along the speculative
path.
Similarly, if a function pointer local variable named func were allocated on the stack, then it may be possible to
speculatively modify the address that func refers to when the conditional branch misprediction occurs. This could
result in speculative execution from an arbitrary address when the function pointer is called through.
It should be noted that both of these examples involve speculative modification of stack-allocated indirect branch
pointers. It is possible that speculative modification could also occur for global variables, heap-allocated memory,
and even read-only memory on some CPUs. For stack-allocated memory, the Microsoft C++ compiler already
takes steps to make it more difficult to speculatively modify stack-allocated indirect branch targets, such as by
reordering local variables such that buffers are placed adjacent to a security cookie as part of the /GS compiler
security feature.
class CBaseType {
public:
CBaseType(TypeName type) : type(type) {}
TypeName type;
};
obj2->dispatch_routine();
return obj2->field2;
}
}
unsigned char ReadByte(unsigned char *buffer, unsigned int buffer_size, unsigned int trusted_index) {
unsigned int index;
// SPECULATION BARRIER
unsigned char value = buffer[index];
return shared_buffer[value * 4096];
}
void DispatchMessage(unsigned int untrusted_message_id, unsigned char *buffer, unsigned int buffer_size) {
MESSAGE_ROUTINE routine;
// SPECULATION BARRIER
routine(buffer, buffer_size);
}
Mitigation options
Speculative execution side channel vulnerabilities can be mitigated by making changes to source code. These
changes can involve mitigating specific instances of a vulnerability, such as by adding a speculation barrier, or by
making changes to the design of an application to make sensitive information inaccessible to speculative execution.
Speculation barrier via manual instrumentation
A speculation barrier can be manually inserted by a developer to prevent speculative execution from proceeding
along a non-architectural path. For example, a developer can insert a speculation barrier before a dangerous
coding pattern in the body of a conditional block, either at the beginning of the block (after the conditional branch)
or before the first load that is of concern. This will prevent a conditional branch misprediction from executing the
dangerous code on a non-architectural path by serializing execution. The speculation barrier sequence differs by
hardware architecture as described by the following table:
For example, the following code pattern can be mitigated by using the _mm_lfence intrinsic as shown below.
// A pointer to a shared memory region of size 1MB (256 * 4096)
unsigned char *shared_buffer;
unsigned char ReadByte(unsigned char *buffer, unsigned int buffer_size, unsigned int untrusted_index) {
if (untrusted_index < buffer_size) {
_mm_lfence();
unsigned char value = buffer[untrusted_index];
return shared_buffer[value * 4096];
}
}
It should be noted that the index masking performed here could be subject to speculative store bypass depending
on the code that is generated by the compiler.
unsigned char ReadByte(unsigned char *buffer, unsigned int buffer_size, unsigned int untrusted_index) {
if (untrusted_index < buffer_size) {
untrusted_index &= (buffer_size - 1);
unsigned char value = buffer[untrusted_index];
return shared_buffer[value * 4096];
}
}
See also
Guidance to mitigate speculative execution side-channel vulnerabilities
Mitigating speculative execution side channel hardware vulnerabilities
C/C++ language and standard libraries reference
12/18/2020 • 2 minutes to read • Edit Online
This section of the documentation contains reference content for the Microsoft implementation of the ISO standard
C and C++ languages. The language reference includes documentation for the preprocessor, compiler intrinsics,
and supported assembly languages.
You'll also find documentation for the C runtime library, the C++ standard library, and several other libraries
available with the Microsoft C/C++ compiler (MSVC) here.
Language reference
C language
Reference content for the Microsoft implementation of the C language.
C++ language
Reference content for the Microsoft implementation of the C++ language.
C/C++ preprocessor
Reference content for the preprocessor used by C and C++.
Compiler intrinsics
Describes intrinsic functions that are available in Microsoft C and C++ for x86, ARM, ARM64, and x64 architectures.
Inline assembler
Explains how to use the Visual C/C++ inline assembler with x86 processors.
ARM assembler reference
Provides reference material for the Microsoft ARM assembler (ARMASM) and related tools.
Microsoft macro assembler reference
Provides reference material for the Microsoft Macro assembler (MASM).
Libraries reference
Standard libraries
C runtime library
The reference for the Microsoft implementation of the C runtime library (CRT), sometimes referred to as the
Universal CRT.
C++ standard library
The reference for the Microsoft implementation of the C++ standard library.
Libraries for Windows applications
MFC/ATL
Documentation for the Microsoft Foundation Classes (MFC) and Active Template Library (ATL) class libraries.
Additional libraries
C++ AMP (C++ Accelerated Massive Parallelism)
Classes that enable the use of modern graphics processors for general purpose programming.
Concurrency Runtime
Classes that simplify the writing of programs that use data parallelism or task parallelism.
OpenMP
Reference for the Microsoft implementation of the OpenMP API.
SafeInt library
A portable library that can be used with MSVC, GCC, or Clang to help prevent integer overflows.
Data Access Libraries Libraries to support data access using ATL or MFC, and legacy services such as OLE DB and
ODBC.
Related articles
Windows Runtime (WinRT) with C++
C++/WinRT is an entirely standard modern C++17 language projection for Windows Runtime (WinRT) APIs,
implemented as a header-file-based library.
Windows Runtime C++ Template Library (WRL)
A legacy template library for the Windows Runtime, replaced by C++/WinRT.
Languages
12/18/2020 • 2 minutes to read • Edit Online
C Language
C++ Language
C/C++ Preprocessor
Compiler Intrinsics and Assembly Language
C Language Reference
12/18/2020 • 2 minutes to read • Edit Online
The C Language Reference describes the C programming language as implemented in Microsoft C. The book's
organization is based on the ANSI C standard (sometimes referred to as C89) with additional material on the
Microsoft extensions to the ANSI C standard.
Organization of the C Language Reference
For additional reference material on C++ and the preprocessor, see:
C++ Language Reference
Preprocessor Reference
Compiler and linker options are documented in the C/C++ Building Reference.
See also
C++ Language Reference
C++ Language Reference
12/18/2020 • 2 minutes to read • Edit Online
This reference explains the C++ programming language as implemented in the Microsoft C++ compiler. The
organization is based on The Annotated C++ Reference Manual by Margaret Ellis and Bjarne Stroustrup and on
the ANSI/ISO C++ International Standard (ISO/IEC FDIS 14882). Microsoft-specific implementations of C++
language features are included.
For an overview of Modern C++ programming practices, see Welcome Back to C++.
See the following tables to quickly find a keyword or operator:
C++ Keywords
C++ Operators
In This Section
Lexical Conventions
Fundamental lexical elements of a C++ program: tokens, comments, operators, keywords, punctuators, literals.
Also, file translation, operator precedence/associativity.
Basic Concepts
Scope, linkage, program startup and termination, storage classes, and types.
Built-in types The fundamental types that are built into the C++ compiler and their value ranges.
Standard Conversions
Type conversions between built-in types. Also, arithmetic conversions and conversions among pointer, reference,
and pointer-to-member types.
Declarations and definitions Declaring and defining variables, types and functions.
Operators, Precedence and Associativity
The operators in C++.
Expressions
Types of expressions, semantics of expressions, reference topics on operators, casting and casting operators, run-
time type information.
Lambda Expressions
A programming technique that implicitly defines a function object class and constructs a function object of that
class type.
Statements
Expression, null, compound, selection, iteration, jump, and declaration statements.
Classes and structs
Introduction to classes, structures, and unions. Also, member functions, special member functions, data members,
bit fields, this pointer, nested classes.
Unions
User-defined types in which all members share the same memory location.
Derived Classes
Single and multiple inheritance, virtual functions, multiple base classes, abstract classes, scope rules. Also, the
__super and __interface keywords.
Member-Access Control
Controlling access to class members: public , private , and protected keywords. Friend functions and classes.
Overloading
Overloaded operators, rules for operator overloading.
Exception Handling
C++ exception handling, structured exception handling (SEH), keywords used in writing exception handling
statements.
Assertion and User-Supplied Messages
#error directive, the static_assert keyword, the assert macro.
Templates
Template specifications, function templates, class templates, typename keyword, templates vs. macros, templates
and smart pointers.
Event Handling
Declaring events and event handlers.
Microsoft-Specific Modifiers
Modifiers specific to Microsoft C++. Memory addressing, calling conventions, naked functions, extended
storage-class attributes ( __declspec ), __w64 .
Inline Assembler
Using assembly language and C++ in __asm blocks.
Compiler COM Support
A reference to Microsoft-specific classes and global functions used to support COM types.
Microsoft Extensions
Microsoft extensions to C++.
Nonstandard Behavior
Information about nonstandard behavior of the Microsoft C++ compiler.
Welcome Back to C++
An overview of modern C++ programming practices for writing safe, correct and efficient programs.
Related Sections
Component Extensions for Runtime Platforms
Reference material on using the Microsoft C++ compiler to target .NET.
C/C++ Building Reference
Compiler options, linker options, and other build tools.
C/C++ Preprocessor Reference
Reference material on pragmas, preprocessor directives, predefined macros, and the preprocessor.
Visual C++ Libraries
A list of links to the reference start pages for the various Microsoft C++ libraries.
See also
C Language Reference
C/C++ preprocessor reference
11/2/2020 • 2 minutes to read • Edit Online
The C/C++ preprocessor reference explains the preprocessor as it is implemented in Microsoft C/C++. The
preprocessor performs preliminary operations on C and C++ files before they are passed to the compiler. You can
use the preprocessor to conditionally compile code, insert files, specify compile-time error messages, and apply
machine-specific rules to sections of code.
In Visual Studio 2019 the /Zc:preprocessor compiler option provides a fully conformant C11 and C17
preprocessor. This is the default when you use the compiler flag /std:c11 or /std:c17 .
In this section
Preprocessor
Provides an overview of the traditional and new conforming preprocessors.
Preprocessor directives
Describes directives, typically used to make source programs easy to change and easy to compile in different
execution environments.
Preprocessor operators
Discusses the four preprocessor-specific operators used in the context of the #define directive.
Predefined macros
Discusses predefined macros as specified by the C and C++ standards and by Microsoft C++.
Pragmas
Discusses pragmas, which offer a way for each compiler to offer machine- and operating system-specific features
while retaining overall compatibility with the C and C++ languages.
Related sections
C++ language reference
Provides reference material for the Microsoft implementation of the C++ language.
C language reference
Provides reference material for the Microsoft implementation of the C language.
C/C++ build reference
Provides links to topics discussing compiler and linker options.
Visual Studio projects - C++
Describes the user interface in Visual Studio that enables you to specify the directories that the project system will
search to locate files for your C++ project.
Compiler intrinsics and assembly language
12/18/2020 • 2 minutes to read • Edit Online
This section of the documentation contains information about compiler intrinsics and the assembly language.
Related articles
T IT L E DESC RIP T IO N
Inline assembler Explains how to use the Visual C/C++ inline assembler with
x86 processors.
ARM assembler reference Provides reference material for the Microsoft ARM assembler
(armasm) and related tools.
Microsoft Macro Assembler reference Provides reference material for the Microsoft Macro assembler
(masm).
C++ in Visual Studio The top-level article for Visual C++ documentation.
Compiler intrinsics
12/18/2020 • 2 minutes to read • Edit Online
Most functions are contained in libraries, but some functions are built in (that is, intrinsic) to the compiler. These
are referred to as intrinsic functions or intrinsics.
Remarks
If a function is an intrinsic, the code for that function is usually inserted inline, avoiding the overhead of a function
call and allowing highly efficient machine instructions to be emitted for that function. An intrinsic is often faster
than the equivalent inline assembly, because the optimizer has a built-in knowledge of how many intrinsics
behave, so some optimizations can be available that are not available when inline assembly is used. Also, the
optimizer can expand the intrinsic differently, align buffers differently, or make other adjustments depending on
the context and arguments of the call.
The use of intrinsics affects the portability of code, because intrinsics that are available in Visual C++ might not be
available if the code is compiled with other compilers and some intrinsics that might be available for some target
architectures are not available for all architectures. However, intrinsics are usually more portable than inline
assembly. The intrinsics are required on 64-bit architectures where inline assembly is not supported.
Some intrinsics, such as __assume and __ReadWriteBarrier , provide information to the compiler, which affects the
behavior of the optimizer.
Some intrinsics are available only as intrinsics, and some are available both in function and intrinsic
implementations. You can instruct the compiler to use the intrinsic implementation in one of two ways, depending
on whether you want to enable only specific functions or you want to enable all intrinsics. The first way is to use
#pragma intrinsic( intrinsic-function-name-list ) . The pragma can be used to specify a single intrinsic or multiple
intrinsics separated by commas. The second is to use the /Oi (Generate intrinsic functions) compiler option, which
makes all intrinsics on a given platform available. Under /Oi , use #pragma function( intrinsic-function-name-list )
to force a function call to be used instead of an intrinsic. If the documentation for a specific intrinsic notes that the
routine is only available as an intrinsic, then the intrinsic implementation is used regardless of whether /Oi or
#pragma intrinsic is specified. In all cases, /Oi or #pragma intrinsic allows, but does not force, the optimizer to
use the intrinsic. The optimizer can still call the function.
Some standard C/C++ library functions are available in intrinsic implementations on some architectures. When
calling a CRT function, the intrinsic implementation is used if /Oi is specified on the command line.
A header file, <intrin.h>, is available that declares prototypes for the common intrinsic functions. Manufacturer-
specific intrinsics are available in the <immintrin.h> and <ammintrin.h> header files. Additionally, certain
Windows headers declare functions that map onto a compiler intrinsic.
The following sections list all intrinsics that are available on various architectures. For more information on how
the intrinsics work on your particular target processor, refer to the manufacturer's reference documentation.
ARM intrinsics
ARM64 intrinsics
x86 intrinsics list
x64 (amd64) Intrinsics List
Intrinsics available on all architectures
Alphabetical listing of intrinsic functions
See also
ARM assembler reference
Microsoft Macro Assembler reference
Keywords
C run-time library reference
ARM Assembler Reference
12/18/2020 • 2 minutes to read • Edit Online
The articles in this section of the documentation provide reference material for the Microsoft ARM assembler
(armasm) and related tools.
Related Articles
T IT L E DESC RIP T IO N
ARM Assembler Diagnostic Messages Describes commonly encountered armasm warning and error
messages.
ARM Assembler Directives Describes the ARM directives that are different in armasm.
ARM Architecture Reference Manual on the ARM Developer Choose the relevant manual for your ARM architecture. Each
website. contains reference sections about ARM, Thumb, NEON, and
VFP, and additional information about the ARM assembly
language.
ARM Compiler armasm User Guide on the ARM Developer Choose a recent version to find up-to-date information about
website. the ARM assembly language. Note: The "armasm" assembler
that is referred to on the ARM Developer website is not the
Microsoft armasm assembler that is included in Visual Studio
and is documented in this section.
See also
ARM intrinsics
ARM64 intrinsics
Compiler intrinsics
Inline Assembler
12/18/2020 • 2 minutes to read • Edit Online
Microsoft Specific
Assembly language serves many purposes, such as improving program speed, reducing memory needs, and
controlling hardware. You can use the inline assembler to embed assembly-language instructions directly in your
C and C++ source programs without extra assembly and link steps. The inline assembler is built into the compiler,
so you don't need a separate assembler such as the Microsoft Macro Assembler (MASM).
NOTE
Programs with inline assembler code are not fully portable to other hardware platforms. If you are designing for portability,
avoid using inline assembler.
Inline assembly is not supported on the ARM and x64 processors. The following topics explain how to use the
Visual C/C++ inline assembler with x86 processors:
Inline Assembler Overview
Advantages of Inline Assembly
__asm
Using Assembly Language in __asm Blocks
Using C or C++ in __asm Blocks
Using and Preserving Registers in Inline Assembly
Jumping to Labels in Inline Assembly
Calling C Functions in Inline Assembly
Calling C++ Functions in Inline Assembly
Defining __asm Blocks as C Macros
Optimizing Inline Assembly
END Microsoft Specific
See also
Compiler Intrinsics and Assembly Language
C++ Language Reference
Microsoft Macro Assembler reference
12/18/2020 • 2 minutes to read • Edit Online
The Microsoft Macro Assembler (MASM) provides several advantages over inline assembly. MASM contains a
macro language that has features such as looping, arithmetic, and text string processing. MASM also gives you
greater control over the hardware because it supports the instruction sets of the 386, 486, and Pentium
processors. By using MASM, you also can reduce time and memory overhead.
In This Section
ML and ML64 command-line option
Describes the ML.exe and ML64.exe command-line options.
ML error messages
Describes ML.exe fatal and nonfatal error messages and warnings.
Directives reference
Provides links to articles that discuss the use of directives in MASM.
Symbols Reference
Provides links to articles that discuss the use of symbols in MASM.
Operators Reference
Provides links to articles that discuss the use of operators in MASM.
Processor Manufacturer Programming Manuals
Provides links to websites that may contain programming information about processors that are not
manufactured, sold, or supported by Microsoft.
MASM for x64 (ml64.exe)
Information about how to create output files for x64.
MASM BNF Grammar
Formal BNF description of MASM for x64.
Related Sections
C++ in Visual Studio
Provides links to different areas of the Visual Studio and Visual C++ documentation.
See also
Compiler Intrinsics
x86Intrinsics
x64 (amd64) Intrinsics
Component Extensions for .NET and UWP
12/18/2020 • 5 minutes to read • Edit Online
The C++ standard allows compiler vendors to provide non-standard extensions to the language. Microsoft
provides extensions to help you connect native C++ code to code that runs on the .NET Framework or the
Universal Windows Platform (UWP). The .NET extensions are called C++/CLI and produce code that executes in the
.NET managed execution environment that is called the Common Language Runtime (CLR). The UWP extensions
are called C++/CX and they produce native machine code.
NOTE
For new applications, we recommend using C++/WinRT rather than C++/CX. C++/WinRT is a new, standard C++17
language projection for Windows Runtime APIs. We will continue to support C++/CX and WRL, but highly recommend that
new applications use C++/WinRT. For more information, see C++/WinRT.
ref struct
value struct
interface struct
K EY W O RD C O N T EXT SEN SIT IVE P URP O SE REF EREN C E
enum struct
Override Specifiers
You can use the following keywords to qualify override behavior for derivation. Although the new keyword is not
an extension of C++, it is listed here because it can be used in an additional context. Some specifiers are also valid
for native programming. For more information, see How to: Declare Override Specifiers in Native Compilations
(C++/CLI).
Miscellaneous Keywords
The following keywords have been added to the C++ extensions.
K EY W O RD C O N T EXT SEN SIT IVE P URP O SE REF EREN C E
Template Constructs
The following language constructs are implemented as templates, instead of as keywords. If you specify the /ZW
compiler option, they are defined in the lang namespace. If you specify the /clr compiler option, they are
defined in the cli namespace.
Declarators
The following type declarators instruct the runtime to automatically manage the lifetime and deletion of allocated
objects.
TO P IC DESC RIP T IO N
__identifier (C++/CLI) (Windows Runtime and CLR) Enables the use of keywords as
identifiers.
Variable Argument Lists (...) (C++/CLI) (Windows Runtime and CLR) Enables a function to take a
variable number of arguments.
.NET Framework Equivalents to C++ Native Types (C++/CLI) Lists the CLR types that are used in place of C++ integral
types.
appdomain __declspec modifier __declspec modifier that mandates that static and global
variables exist per appdomain.
C-Style Casts with /clr (C++/CLI) Describes how C-style casts are interpreted.
Friend Assemblies (C++) Discusses how a client assembly can access all types in an
assembly component.
Compiler Support for Type Traits Discusses how to detect characteristics of types at compile
time.
managed, unmanaged pragmas Demonstrates how managed and unmanaged functions can
co-exist in the same module.
TO P IC DESC RIP T IO N
process __declspec modifier __declspec modifier that mandates that static and global
variables exist per process.
See also
.NET Programming with C++/CLI (Visual C++)
Native and .NET Interoperability
C++ Attributes for COM and .NET
12/18/2020 • 4 minutes to read • Edit Online
Microsoft defines a set of C++ attributes that simplify COM programming and .NET Framework common language
runtime development. When you include attributes in your source files, the compiler works with provider DLLs to
insert code or modify the code in the generated object files. These attributes aid in the creation of .idl files,
interfaces, type libraries, and other COM elements. In the integrated development environment (IDE), attributes are
supported by the wizards and by the Properties window.
While attributes eliminate some of the detailed coding needed to write COM objects, you need a background in
COM fundamentals to best use them.
NOTE
If you are looking for C++ standard attributes, see Attributes.
Purpose of Attributes
Attributes extend C++ in directions not currently possible without breaking the classic structure of the language.
Attributes allow providers (separate DLLs) to extend language functionality dynamically. The primary goal of
attributes is to simplify the authoring of COM components, in addition to increasing the productivity level of the
component developer. Attributes can be applied to nearly any C++ construct, such as classes, data members, or
member functions. The following is a highlight of benefits provided by this new technology:
Exposes a familiar and simple calling convention.
Uses inserted code, which, unlike macros, is recognized by the debugger.
Allows easy derivation from base classes without burdensome implementation details.
Replaces the large amount of IDL code required by a COM component with a few concise attributes.
For example, to implement a simple event sink for a generic ATL class, you could apply the event_receiver attribute
to a specific class such as CMyReceiver . The event_receiver attribute is then compiled by the Microsoft C++
compiler, which inserts the proper code into the object file.
[event_receiver(com)]
class CMyReceiver
{
void handler1(int i) { ... }
void handler2(int i, float j) { ... }
}
You can then set up the CMyReceiver methods handler1 and handler2 to handle events (using the intrinsic
function __hook) from an event source, which you can create using event_source.
NOTE
Attribute usage does not alter the contents of the source file. The only time the generated attribute code is visible is during
debugging sessions. In addition, for each source file in the project, you can generate a text file that displays the results of the
attribute substitution. For more information on this procedure, see /Fx (Merge Injected Code) and Debugging Injected Code.
Like most C++ constructs, attributes have a set of characteristics that defines their proper usage. This is referred to
as the context of the attribute and is addressed in the attribute context table for each attribute reference topic. For
example, the coclass attribute can only be applied to an existing class or structure, as opposed to the cpp_quote
attribute, which can be inserted anywhere within a C++ source file.
Attribute Contexts
C++ attributes can be described using four basic fields: the target they can be applied to (Applies To ), if they are
repeatable or not (Repeatable ), the required presence of other attributes (Required Attributes ), and
incompatibilities with other attributes (Invalid Attributes ). These fields are listed in an accompanying table in
each attribute's reference topic. Each of these fields is described below.
Applies To
This field describes the different C++ language elements that are legal targets for the specified attribute. For
instance, if an attribute specifies "class" in the Applies To field, this indicates that the attribute can only be applied
to a legal C++ class. If the attribute is applied to a member function of a class, a syntax error would result.
For more information, see Attributes by Usage.
Repeatable
This field states whether the attribute can be repeatedly applied to the same target. The majority of attributes are
not repeatable.
Required Attributes
This field lists other attributes that need to be present (that is, applied to the same target) for the specified attribute
to function properly. It is uncommon for an attribute to have any entries for this field.
Invalid Attributes
This field lists other attributes that are incompatible with the specified attribute. It is uncommon for an attribute to
have any entries for this field.
In This Section
Attribute Programming FAQ
Attributes by Group
Attributes by Usage
Attributes Alphabetical Reference
Libraries
12/18/2020 • 2 minutes to read • Edit Online
Visual Studio includes the following libraries when you install one or more of the C++ workloads. For information
about installing 3rd-party libraries, see vcpkg: A C++ package manager for Windows, Linux and MacOS.
Standard Libraries
C Runtime Library
C++ Standard Library
SafeInt Library
OpenMP
The Microsoft runtime library provides routines for programming for the Microsoft Windows operating system.
These routines automate many common programming tasks that are not provided by the C and C++ languages.
Sample programs are included in the individual reference topics for most routines in the library.
In This Section
C Runtime libraries
Discusses the .lib files that comprise the C runtime libraries.
Universal C runtime routines by category
Provides links to the runtime library by category.
Global variables and standard types
Provides links to the global variables and standard types provided by the runtime library.
Global constants
Provides links to the global constants defined by the runtime library.
Global state
Describes the scope of global state in the C runtime library.
Generic-text mappings
Provides links to the generic-text mappings defined in Tchar.h.
Alphabetical function reference
Provides links to the C runtime library functions, organized alphabetically.
Function family overviews
Provides links to the C runtime library functions, organized by function family.
Language and country/region strings
Describes how to use the setlocale function to set the language and Country/Region strings.
Related Sections
Debug routines
Provides links to the debug versions of the runtime library routines.
Runtime error checking
Provides links to functions that support runtime error checks.
DLLs and Visual C++ runtime library behavior
Discusses the entry point and startup code used for a DLL.
Debugging
Provides links to using the Visual Studio debugger to correct logic errors in your application or stored procedures.
C++ Standard Library Reference
12/18/2020 • 2 minutes to read • Edit Online
A C++ program can call on a large number of functions from this conforming implementation of the C++
Standard Library. These functions perform essential services such as input and output and provide efficient
implementations of frequently used operations.
For more information about Visual C++ run-time libraries, see CRT Library Features.
In This Section
C++ Standard Library Overview
Provides an overview of the Microsoft implementation of the C++ Standard Library.
iostream Programming
Provides an overview of iostream programming.
Header Files Reference
Provides links to reference topics discussing the C++ Standard Library header files, with code examples.
SafeInt Library
12/18/2020 • 2 minutes to read • Edit Online
SafeInt is a portable library that can be used with MSVC, GCC or Clang to help prevent integer overflows that
might result when the application performs mathematical operations. The latest version of this library is located at
https://github.com/dcleblanc/SafeInt.
In This Section
SEC T IO N DESC RIP T IO N
SafeInt Functions Functions that can be used without creating a SafeInt object.
Related Sections
SEC T IO N DESC RIP T IO N
C++ Language Reference Reference and conceptual content for the C++ language.
SafeInt Class
12/18/2020 • 9 minutes to read • Edit Online
Extends the integer primitives to help prevent integer overflow and lets you compare different types of integers.
NOTE
The latest version of the SafeInt library is located at https://github.com/dcleblanc/SafeInt. To use the SafeInt library, clone the
repo and #include "SafeInt.hpp"
Syntax
template<typename T, typename E = _SAFEINT_DEFAULT_ERROR_POLICY>
class SafeInt;
Parameters
T
The type of integer or Boolean parameter that SafeInt replaces.
E
An enumerated data type that defines the error handling policy.
U
The type of integer or Boolean parameter for the secondary operand.
rhs
[in] An input parameter that represents the value on the right side of the operator in several stand-alone functions.
i
[in] An input parameter that represents the value on the right side of the operator in several stand-alone functions.
bits
[in] An input parameter that represents the value on the right side of the operator in several stand-alone functions.
Members
Public Constructors
NAME DESC RIP T IO N
Assignment Operators
NAME SY N TA X
= template<typename U>
SafeInt<T,E>& operator= (const U& rhs)
= template<typename U>
SafeInt<T,E>& operator= (const SafeInt<U, E>& rhs)
Casting Operators
NAME SY N TA X
Comparison Operators
NAME SY N TA X
== template<typename U>
!= template<typename U>
Arithmetic Operators
NAME SY N TA X
++ SafeInt<T,E>& operator++ ()
-- SafeInt<T,E>& operator-- ()
% template<typename U>
%= template<typename U>
%= template<typename U>
* template<typename U>
*= template<typename U>
*= template<typename U>
/ template<typename U>
/= template<typename U>
SafeInt<T,E>& operator/= (U i)
/= template<typename U>
+ template<typename U>
+= template<typename U>
+= template<typename U>
- template<typename U>
-= template<typename U>
-= template<typename U>
Logical Operators
NAME SY N TA X
^ template<typename U>
^= template<typename U>
^= template<typename U>
| template<typename U>
|= template<typename U>
|= template<typename U>
Remarks
The SafeInt class protects against integer overflow in mathematical operations. For example, consider adding
two 8-bit integers: one has a value of 200 and the second has a value of 100. The correct mathematical operation
would be 200 + 100 = 300. However, because of the 8-bit integer limit, the upper bit will be lost and the compiler
will return 44 (300 - 28) as the result. Any operation that depends on this mathematical equation will generate
unexpected behavior.
The SafeInt class checks whether an arithmetic overflow occurs or whether the code tries to divide by zero. In
both cases, the class calls the error handler to warn the program of the potential problem.
This class also lets you compare two different types of integers as long as they are SafeInt objects. Typically,
when you do a comparison, you must first convert the numbers to be the same type. Casting one number to
another type often requires checks to make sure that there is no loss of data.
The Operators table in this topic lists the mathematical and comparison operators supported by the SafeInt class.
Most mathematical operators return a SafeInt object of type T .
Comparison operations between a SafeInt and an integral type can be performed in either direction. For
example, both SafeInt<int>(x) < y and y> SafeInt<int>(x) are valid and will return the same result.
Many binary operators don't support using two different SafeInt types. One example of this is the & operator.
SafeInt<T, E> & int is supported, but SafeInt<T, E> & SafeInt<U, E> isn't. In the latter example, the compiler
does not know what type of parameter to return. One solution to this problem is to cast the second parameter
back to the base type. By using the same parameters, this can be done with SafeInt<T, E> & (U)SafeInt<U, E> .
NOTE
For any bitwise operations, the two different parameters should be the same size. If the sizes differ, the compiler will throw
an ASSERT exception. The results of this operation can't be guaranteed to be accurate. To resolve this issue, cast the smaller
parameter until it's the same size as the larger parameter.
For the shift operators, shifting more bits than exist for the template type will throw an ASSERT exception. This will
have no effect in release mode. Mixing two types of SafeInt parameters is possible for the shift operators because
the return type is the same as the original type. The number on the right side of the operator only indicates the
number of bits to shift.
When you do a logical comparison with a SafeInt object, the comparison is strictly arithmetic. For example,
consider these expressions:
SafeInt<uint>((uint)~0) > -1
((uint)~0) > -1
The first statement resolves to true , but the second statement resolves to false . The bitwise negation of 0 is
0xFFFFFFFF. In the second statement, the default comparison operator compares 0xFFFFFFFF to 0xFFFFFFFF and
considers them to be equal. The comparison operator for the SafeInt class realizes that the second parameter is
negative whereas the first parameter is unsigned. Therefore, although the bit representation is identical, the
SafeInt logical operator realizes that the unsigned integer is larger than -1.
Be careful when you use the SafeInt class together with the ?: ternary operator. Consider the following line of
code.
If flag is false , the compiler throws an exception instead of assigning the value of -1 to x . Therefore, to avoid
this behavior, the correct code to use is the following line.
T and U can be assigned a Boolean type, character type, or integer type. The integer types can be signed or
unsigned and any size from 8 bits to 64 bits.
NOTE
Although the SafeInt class accepts any kind of integer, it performs more efficiently with unsigned types.
E is the error handling mechanism that SafeInt uses. Two error handling mechanisms are provided with the
SafeInt library. The default policy is SafeIntErrorPolicy_SafeIntException , which throws a SafeIntException Class
exception when an error occurs. The other policy is SafeIntErrorPolicy_InvalidParameter , which stops the program
if an error occurs.
There are two options to customize the error policy. The first option is to set the parameter E when you create a
SafeInt . Use this option when you want to change the error handling policy for just one SafeInt . The other
option is to define _SAFEINT_DEFAULT_ERROR_POLICY to be your customized error-handling class before you
include the SafeInt library. Use this option when you want to change the default error handling policy for all
instances of the SafeInt class in your code.
NOTE
A customized class that handles errors from the SafeInt library should not return control to the code that called the error
handler. After the error handler is called, the result of the SafeInt operation can't be trusted.
Inheritance Hierarchy
SafeInt
Requirements
Header : SafeInt.hpp
NOTE
The latest version of this library is located at https://github.com/dcleblanc/SafeInt. Clone the library and include SafeInt.hpp
to use the SafeInt library. Prefer this github repo to <safeint.h>. it's a modern version of <safeint.h> that includes a small
number of bug fixes, uses modern features of C++ resulting in more efficient code, and is portable to any platform using
gcc, clang, or Intel compilers.
Example
#include "SafeInt.hpp" // set path to your clone of the SafeInt GitHub repo
(https://github.com/dcleblanc/SafeInt)
int main()
{
int divisor = 3;
int dividend = 6;
int result;
Namespace: none
SafeInt::SafeInt
Constructs a SafeInt object.
SafeInt() throw
Parameters
i
[in] The value for the new SafeInt object. This must be a parameter of type T or U, depending on the constructor.
b
[in] The Boolean value for the new SafeInt object.
u
[in] A SafeInt of type U. The new SafeInt object will have the same value as u, but will be of type T.
U The type of data stored in the SafeInt . This can be either a Boolean, character, or integer type. If it's an integer
type, it can be signed or unsigned and be between 8 and 64 bits.
Remarks
The input parameter for the constructor, i or u, must be a Boolean, character, or integer type. If it's another type of
parameter, the SafeInt class calls static_assert to indicate an invalid input parameter.
The constructors that use the template type U automatically convert the input parameter to the type specified by
T . The SafeInt class converts the data without any loss of data. It reports to the error handler E if it can't
convert the data to type T without data loss.
If you create a SafeInt from a Boolean parameter, you need to initialize the value immediately. You can't construct
a SafeInt using the code SafeInt<bool> sb; . This will generate a compile error.
SafeInt Functions
12/18/2020 • 5 minutes to read • Edit Online
The SafeInt library provides several functions that you can use without creating an instance of the SafeInt class. If
you want to protect a single mathematical operation from integer overflow, you can use these functions. If you
want to protect multiple mathematical operations, you should create SafeInt objects. It's more efficient to create
SafeInt objects than to use these functions multiple times.
These functions enable you to compare or perform mathematical operations on two different types of parameters
without having to convert them to the same type first.
Each of these functions has two template types: T and U . Each of these types can be a Boolean, character, or
integral type. Integral types can be signed or unsigned and any size from 8 bits to 64 bits.
NOTE
The latest version of this library is located at https://github.com/dcleblanc/SafeInt.
In This Section
F UN C T IO N DESC RIP T IO N
SafeEquals, SafeGreaterThan, SafeGreaterThanEquals, Compares two numbers. These functions enable you to
SafeLessThan, SafeLessThanEquals, SafeNotEquals compare two different types of numbers without changing
their types.
Related Sections
SEC T IO N DESC RIP T IO N
SafeAdd
Adds two numbers in a way that protects against overflow.
Parameters
t
[in] The first number to add. This must be of type T.
u
[in] The second number to add. This must be of type U.
result
[out] The parameter where SafeAdd stores the result.
Return Value
true if no error occurs; false if an error occurs.
SafeCast
Casts one type of number to another type.
Parameters
From
[in] The source number to convert. This must be of type T .
To
[out] A reference to the new number type. This must be of type U .
Return Value
true if no error occurs; false if an error occurs.
SafeDivide
Divides two numbers in a way that protects against dividing by zero.
Parameters
t
[in] The dividend. This must be of type T.
u
[in] The divisor. This must be of type U.
result
[out] The parameter where SafeDivide stores the result.
Return Value
true if no error occurs; false if an error occurs.
SafeEquals
Compares two numbers to determine whether they're equal.
Parameters
t
[in] The first number to compare. This must be of type T.
u
[in] The second number to compare. This must be of type U.
Return Value
true if t and u are equal; otherwise false .
Remarks
The method enhances == because SafeEquals enables you to compare two different types of numbers.
SafeGreaterThan
Compares two numbers.
Parameters
t
[in] The first number to compare. This must be of type T .
u
[in] The second number to compare. This must be of type U .
Return Value
true if t is greater than u; otherwise false .
Remarks
SafeGreaterThan extends the regular comparison operator by enabling you to compare two different types of
numbers.
SafeGreaterThanEquals
Compares two numbers.
Parameters
t
[in] The first number to compare. This must be of type T .
u
[in] The second number to compare. This must be of type U .
Return Value
true if t is greater than or equal to u; otherwise false .
Remarks
SafeGreaterThanEquals enhances the standard comparison operator because it enables you to compare two
different types of numbers.
SafeLessThan
Determines whether one number is less than another.
Parameters
t
[in] The first number. This must be of type T .
u
[in] The second number. This must be of type U .
Return Value
true if t is less than u; otherwise false .
Remarks
This method enhances the standard comparison operator because SafeLessThan enables you to compare two
different types of number.
SafeLessThanEquals
Compares two numbers.
template <typename T, typename U>
inline bool SafeLessThanEquals (
const T t,
const U u
) throw ();
Parameters
t
[in] The first number to compare. This must be of type T .
u
[in] The second number to compare. This must be of type U .
Return Value
true if t is less than or equal to u; otherwise false .
Remarks
SafeLessThanEquals extends the regular comparison operator by enabling you to compare two different types of
numbers.
SafeModulus
Performs the modulus operation on two numbers.
Parameters
t
[in] The divisor. This must be of type T .
u
[in] The dividend. This must be of type U .
result
[out] The parameter where SafeModulus stores the result.
Return Value
true if no error occurs; false if an error occurs.
SafeMultiply
Multiplies two numbers together in a way that protects against overflow.
SafeNotEquals
Determines if two numbers aren't equal.
Parameters
t
[in] The first number to compare. This must be of type T .
u
[in] The second number to compare. This must be of type U .
Return Value
true if t and u aren't equal; otherwise false .
Remarks
The method enhances != because SafeNotEquals enables you to compare two different types of numbers.
SafeSubtract
Subtracts two numbers in a way that protects against overflow.
Parameters
t
[in] The first number in the subtraction. This must be of type T .
u
[in] The number to subtract from t. This must be of type U .
result
[out] The parameter where SafeSubtract stores the result.
Return Value
true if no error occurs; false if an error occurs.
SafeIntException Class
12/18/2020 • 2 minutes to read • Edit Online
The SafeInt class uses SafeIntException to identify why a mathematical operation cannot be completed.
NOTE
The latest version of this library is located at https://github.com/dcleblanc/SafeInt.
Syntax
class SafeIntException;
Members
Public Constructors
NAME DESC RIP T IO N
Remarks
The SafeInt class is the only class that uses the SafeIntException class.
Inheritance Hierarchy
SafeIntException
Requirements
Header : safeint.h
Namespace: msl::utilities
SafeIntException::SafeIntException
Creates a SafeIntException object.
SafeIntException();
SafeIntException(
SafeIntError code
);
Parameters
code
[in] An enumerated data value that describes the error that occurred.
Remarks
The possible values for code are defined in the file Safeint.h. For convenience, the possible values are also listed
here.
SafeIntNoError
SafeIntArithmeticOverflow
SafeIntDivideByZero
MFC and ATL
12/18/2020 • 2 minutes to read • Edit Online
The Microsoft Foundation Classes (MFC) provide a C++ object-oriented wrapper over Win32 for rapid
development of native desktop applications. The Active Template Library (ATL) is a wrapper library that simplifies
COM development and is used extensively for creating ActiveX controls.
You can create MFC or ATL programs with Visual Studio Community Edition or higher. The Express editions do not
support MFC or ATL.
In Visual Studio 2015, Visual C++ is an optional component, and MFC and ATL components are optional sub-
components under Visual C++. If you do not select these components when you first install Visual Studio, you will
be prompted to install them the first time you attempt to create or open an MFC or ATL project.
In Visual Studio 2017 and later, MFC and ATL are optional sub-components under the Desktop development
with C++ workload in the Visual Studio Installer program. You can install ATL support without MFC, or combined
MFC and ATL support (MFC depends on ATL). For more information about workloads and components, see Install
Visual Studio.
Related Articles
T IT L E DESC RIP T IO N
ATL COM Desktop Components ATL provides class templates and other use constructs to
simplify creation of COM objects in C++.
ATL/MFC Shared Classes References for CStringT Class and other classes that are shared
by MFC and ATL.
Working with Resource Files The resource editor lets you edit UI resources such as strings,
images, and dialog boxes.
Visual C++ provides the following technologies to help you create multi-threaded and parallel programs that take
advantage of multiple cores and use the GPU for general purpose programming.
Related Articles
T IT L E DESC RIP T IO N
Concurrency Runtime Classes that simplify the writing of programs that use data
parallelism or task parallelism.
C++ AMP (C++ Accelerated Massive Parallelism) Classes that enable the use of modern graphics processors for
general purpose programming.
Multithreading Support for Older Code (Visual C++) Older technologies that may be useful in older applications.
For new apps, use the Concurrency Runtime or C++ AMP.
C++ in Visual Studio This section of the documentation contains information about
most of the features of Visual C++.
Data Access in Visual C++
12/18/2020 • 2 minutes to read • Edit Online
Virtually all database products, SQL and NoSQL, provide an interface for native C++ applications. The industry
standard interface is ODBC which is supported by all major SQL database products and many NoSQL products.
For non-Microsoft products, consult the vendor for more information. Third-party libraries with various license
terms are also available.
Since 2011 Microsoft has aligned on ODBC as the standard for native applications to connecting to Microsoft SQL
Server databases, both on-premises and in the cloud. For more information, see Data Access Programming (MFC-
ATL). C++/CLI libraries can use either the native ODBC drivers or ADO.NET. For more information, see Data Access
Using ADO.NET (C++/CLI) and Accessing data in Visual Studio.
In This Section
Data Access Programming (MFC/ATL)
Describes legacy data access programming with Visual C++, where the preferred way is to use one of the class
libraries such as the Active Template Class Library (ATL) or Microsoft Foundation Class (MFC) Library, which
simplify working with the database APIs.
Open Database Connectivity (ODBC)
The Microsoft Foundation Classes (MFC) library supplies classes for programming with Open Database
Connectivity (ODBC).
OLE DB Programming
A mostly legacy interface which is still required in some scenarios, specifically when you are programming against
linked servers.
Related Topics
Connect to SQL Database using C and C++
Connect to Azure SQL Database from C or C++ applications.
Microsoft Azure Storage Client Library for C++
Azure Storage is a cloud storage solution for modern applications that rely on durability, availability, and scalability
to meet the needs of their customers. Connect to Azure Storage from C++ by using the Azure Storage Client
Library for C++.
ODBC Driver for SQL Server
The latest ODBC driver provides robust data access to Microsoft SQL Server and Microsoft Azure SQL Database
for C/C++ based applications. Provides support for features including always encrypted, Azure Active Directory,
and AlwaysOn Availability Groups. Also available for MacOS and Linux.
OLE DB Driver for SQL Server
The latest OLE DB driver is a stand-alone data access application programming interface (API) that supports
Microsoft SQL Server and Microsoft Azure SQL Database.
Microsoft Azure C and C++ Developer Center
Azure makes it easy to build C++ applications with increased flexibility, scalability and reliability using tools you
love.
How to use Blob Storage from C++
Azure Blob storage is a service that stores unstructured data in the cloud as objects/blobs. Blob storage can store
any type of text or binary data, such as a document, media file, or application installer. Blob storage is also referred
to as object storage.
ODBC Programmer's Reference
The ODBC interface is designed for use with the C programming language. Use of the ODBC interface spans three
areas: SQL statements, ODBC function calls, and C programming.
See also
C++ in Visual Studio