### Example setup for shared_ptr Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/cpp/how-to-create-and-use-shared-ptr-instances.md Required headers and type declarations for the shared_ptr examples. ```cpp // shared_ptr-examples.cpp // The following examples assume these declarations: #include #include #include #include #include struct MediaAsset { virtual ~MediaAsset() = default; // make it polymorphic }; struct Song : public MediaAsset { std::wstring artist; std::wstring title; Song(const std::wstring& artist_, const std::wstring& title_) : artist{ artist_ }, title{ title_ } {} }; struct Photo : public MediaAsset { std::wstring date; std::wstring location; std::wstring subject; Photo( const std::wstring& date_, const std::wstring& location_, const std::wstring& subject_) : date{ date_ }, location{ location_ }, subject{ subject_ } {} }; using namespace std; int main() { // The examples go here, in order: // Example 1 // Example 2 // Example 3 // Example 4 // Example 6 } ``` -------------------------------- ### gets Example Output Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/c-runtime-library/gets-getws.md Sample output generated by the gets example code. ```Output Hello there!The line entered was: Hello there! ``` -------------------------------- ### Implement CWinApp Print Setup and Help Handlers Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cwinapp-class.md Examples of message map entries for CWinApp command handlers. ```cpp ON_COMMAND( ID_FILE_PRINT_SETUP, OnFilePrintSetup ) ``` ```cpp ON_COMMAND( ID_HELP, OnHelp ) ``` -------------------------------- ### Example: BEGIN_CONNECTION_POINT_MAP usage Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/atl/reference/connection-point-macros.md Demonstrates the start of a connection point map within a class definition. ```cpp BEGIN_CONNECTION_POINT_MAP(CMyClass) CONNECTION_POINT_ENTRY(IID_IPropertyNotifySink) END_CONNECTION_POINT_MAP() ``` -------------------------------- ### Complete Timer Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/cppcx/wrl/how-to-complete-asynchronous-operations-using-wrl.md This complete example demonstrates starting an asynchronous timer, waiting for it to expire using a synchronization event, and printing a message. It includes all necessary WRL and Windows Runtime initializations and object creations. ```cpp #include #include #include #include #include #include #include #include #include #include #include #include using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; using namespace Windows::System::Threading; // RAII wrapper for RoInitialize and RoUninitialize. class RoInitializeWrapper { public: RoInitializeWrapper(RO_INIT_TYPE initType) { HRESULT hr = RoInitialize(initType); if (FAILED(hr)) { // Handle error throw std::runtime_error("Failed to initialize Windows Runtime"); } } ~RoInitializeWrapper() { RoUninitialize(); } }; int main() { // Initialize the Windows Runtime. RoInitializeWrapper initialize(RO_INIT_MULTITHREADED); // Create an event to synchronize the timer callback. ManualResetEvent timerEvent(false); // Get the activation factory for IThreadPoolTimer. ComPtr timerStatics; Hr = GetActivationFactory( HStringReference::HStringReference(RuntimeClass_Windows_System_Threading_ThreadPoolTimer), &timerStatics); if (FAILED(hr)) { wprintf(L"Failed to get activation factory for ThreadPoolTimer. HRESULT: 0x%x\n", hr); return -1; } // Create the timer. ComPtr timer; hr = timerStatics->CreateTimer( Callback( [&](ABI::Windows::System::Threading::ITimerElapsedHandler* sender, ABI::Windows::System::Threading::ITimerElapsedEventArgs* args) -> HRESULT { wprintf(L"Timer elapsed callback executed.\n"); // Signal the event when the timer expires. timerEvent.Set(); return S_OK; }), nullptr, // No timer id needed for this example &timer); if (FAILED(hr)) { wprintf(L"Failed to create timer. HRESULT: 0x%x\n", hr); return -1; } // Set the timer to expire after 2 seconds. // TimeSpan is in 100-nanosecond units. 2 seconds = 2 * 10^7 * 100 nanoseconds. if (SUCCEEDED(hr)) { hr = timer->Period(TimeSpan{ -20000000LL }); } if (FAILED(hr)) { wprintf(L"Failed to set timer period. HRESULT: 0x%x\n", hr); return -1; } wprintf(L"Timer started. Waiting for it to expire...\n"); // Wait for the timer callback to complete. timerEvent.Wait(); wprintf(L"Timer expired and callback completed. Exiting.\n"); // All ComPtr and RAII objects leave scope and are released automatically. return 0; } ``` -------------------------------- ### CMFCRibbonStatusBarPane Usage Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cmfcribbonstatusbarpane-class.md An example demonstrating the usage of various methods in the CMFCRibbonStatusBarPane class, including construction, text alignment, animation setup, and starting animation. ```APIDOC ## Example The following example demonstrates how to use the various methods in the `CMFCRibbonStatusBarPane` class. The example shows how to construct a `CMFCRibbonStatusBarPane` object, set the text alignment of the label of the status bar pane, define the longest text that can be displayed in the status bar pane without truncation, attach to the status bar pane an image list that can be used for animation, and start the animation. [!code-cpp[NVC_MFC_RibbonApp#2](../../mfc/reference/codesnippet/cpp/cmfcribbonstatusbarpane-class_1.cpp)] ``` -------------------------------- ### Complete Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/cppcx/wrl/how-to-activate-and-use-a-windows-runtime-component-using-wrl.md A full implementation demonstrating the activation and usage of a Windows Runtime component. ```cpp #include #include #include #include using namespace ABI::Windows::Foundation; using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; int wmain() { // Initialize the Windows Runtime. RoInitializeWrapper initialize(RO_INIT_MULTITHREADED); if (FAILED(initialize)) { return -1; } // Create an activation factory for the IUriRuntimeClassFactory interface. ComPtr uriFactory; HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_Foundation_Uri).Get(), &uriFactory); if (FAILED(hr)) { return -1; } // Create a string that represents the URI. HString uriString; hr = uriString.Set(L"https://www.microsoft.com"); if (FAILED(hr)) { return -1; } // Create the IUriRuntimeClass object. ComPtr uri; hr = uriFactory->CreateUri(uriString.Get(), &uri); if (FAILED(hr)) { return -1; } // Get the domain part of the URI. HString domainName; hr = uri->get_Domain(domainName.GetAddressOf()); if (FAILED(hr)) { return -1; } // Print the domain name and return. wprintf_s(L"Domain: %s\n", domainName.GetRawBuffer(nullptr)); return 0; } ``` -------------------------------- ### Get GUID of a Library Block with __uuidof Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/cpp/uuidof-operator.md Use __uuidof to retrieve the GUID of a library block defined with the module attribute. Compile with ole32.lib. This example demonstrates retrieving and printing the library's UUID. ```cpp #include "stdio.h" #include "windows.h" [emitidl]; [module(name="MyLib")]; [export] struct stuff { int i; }; int main() { LPOLESTR lpolestr; StringFromCLSID(__uuidof(MyLib), &lpolestr); wprintf_s(L"%s", lpolestr); CoTaskMemFree(lpolestr); } ``` -------------------------------- ### Initialize CMFCFontComboBox with Setup Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cmfcfontcombobox-class.md Initializes the font combo box by enumerating installed fonts that match the specified parameters. This example is part of the New Controls sample. ```cpp #include "afxcontrolbar.h" void SetupFontCombo(CMFCFontComboBox& combo) { // Initialize the font combo box with default settings. combo.Setup(); } ``` ```cpp // Assuming 'm_wndFontCombo' is an instance of CMFCFontComboBox // SetupFontCombo(m_wndFontCombo); // Example with specific parameters: // combo.Setup(DEVICE_FONTTYPE | TRUETYPE_FONTTYPE, ANSI_CHARSET, PROOF_QUALITY); ``` -------------------------------- ### Implement Office 2007 Visual Manager Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cmfcvisualmanageroffice2007-class.md Example demonstrating the initialization of the Office 2007 visual manager. ```cpp CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007)); ``` -------------------------------- ### Compile and link the example application Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/cpp/tutorial-import-stl-named-module.md Commands to compile the source file and link it against the previously generated module object files. ```cmd cl /std:c++latest /EHsc /nologo /W4 stdCompatExample.cpp link stdCompatExample.obj std.obj std.compat.obj ``` -------------------------------- ### CFile Constructor and Open Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cfile-class.md Demonstrates how to use the CFile constructor and the Open method to create and open files with specific modes. Ensure proper exception handling for file operations. ```cpp void CFile_Example(); // The following example demonstrates the CFile constructor and the Open method. // It also shows how to use the CFile::Open member function. void CFile_Example() { // Construct a CFile object and open a file for writing. // The default of CFile::modeCreate and CFile::modeNoTruncate is used. CFile myFile; // CFile::modeCreate creates a new file if it doesn't exist, or opens it if it does. // CFile::modeNoTruncate ensures that if the file exists, it is not truncated. // CFile::shareExclusive denies read and write access to others. // CFile::typeText sets text mode with special processing for carriage return-line feed pairs. if ( myFile.Open( _T("MyOut.dat"), CFile::modeCreate | CFile::modeNoTruncate | CFile::shareExclusive | CFile::typeText ) ) { // file opened successfully myFile.Write( _T("This is a test."), 15 ); myFile.Close(); } else { // an error occurred TRACE( _T("Failed to open file %s, error: %u"), _T("MyOut.dat"), GetLastError() ); } // Construct a CFile object and open a file for reading. // The default of CFile::modeRead is used. CFile myFile2; // CFile::modeRead requests read access only. // CFile::shareDenyWrite denies write access to others. // CFile::typeUnicode sets Unicode mode. if ( myFile2.Open( _T("MyOut.dat"), CFile::modeRead | CFile::shareDenyWrite | CFile::typeUnicode ) ) { // file opened successfully TRACE( _T("File opened for reading.") ); myFile2.Close(); } else { // an error occurred TRACE( _T("Failed to open file %s, error: %u"), _T("MyOut.dat"), GetLastError() ); } } ``` -------------------------------- ### Iterate MFC List Using GetHeadPosition and GetNext Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/accessing-all-members-of-a-collection.md Use `GetHeadPosition` to get the starting position and `GetNext` to iterate through an MFC list. This example uses a typed pointer list derived from `CObList`. ```cpp #include "stdafx.h" #include "MFCCollections.h" void CMyListDoc::OnIterateList() { // Example of iterating through a typed pointer list // derived from CObList. CPerson* pPerson; POSITION pos = m_lstPeople.GetHeadPosition(); while (pos != NULL) { pPerson = (CPerson*)m_lstPeople.GetNext(pos); // Use pPerson... } } ``` -------------------------------- ### CHeaderCtrl::SetFocusedItem Example Setup Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cheaderctrl-class.md Defines a variable to access the current header control. This is a setup for subsequent examples. ```cpp #include "afxcontrolbar.h" // CHeaderCtrl_s4.h class CHeaderCtrl_s4 : public CHeaderCtrl { public: //{{AFX_VIRTUAL(CHeaderCtrl_s4) //}} DECLARE_DYNAMIC(CHeaderCtrl_s4) protected: //{{AFX_MSG(CHeaderCtrl_s4) //}} DECLARE_MESSAGE_MAP() }; // CHeaderCtrl_s4 message handlers ``` -------------------------------- ### Example output for _open Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/c-runtime-library/reference/open-wopen.md The expected console output after running the provided _open example. ```Output Open succeeded on input file Open succeeded on output file ``` -------------------------------- ### Get slice start index Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/slice-class.md Retrieves the starting index of a slice object. ```cpp size_t start() const; ``` ```cpp // slice_start.cpp // compile with: /EHsc #include #include int main( ) { using namespace std; int i; size_t startVAR; valarray va ( 20 ), vaResult; for ( i = 0 ; i < 20 ; i += 1 ) va [ i ] = i+1; cout << "The operand valarray va is:\n ( "; for ( i = 0 ; i < 20 ; i++ ) cout << va [ i ] << " "; cout << ")." << endl; slice vaSlice ( 3 , 6 , 3 ); vaResult = va [ vaSlice ]; cout << "The slice of valarray va is vaResult = " << "va[slice( 3, 6, 3)] =\n ( "; for ( i = 0 ; i < 6 ; i++ ) cout << vaResult [ i ] << " "; cout << ")." << endl; startVAR = vaSlice.start ( ); cout << "The start index of slice vaSlice is: " << startVAR << "." << endl; } ``` -------------------------------- ### Create Setup Batch File Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/windows/deploying-visual-cpp-application-by-using-the-vcpp-redistributable-package.md This batch file installs the Visual C++ Redistributable for the target architecture and copies the application to the Program Files directory. Uncomment the appropriate Redistributable line for your target architecture. Ensure 'MyMFCApp' matches your application's name and adjust 'Program Files' for x86 targets. ```cmd @echo off REM Choose one of the following Redistributable files to install ::vc_redist.x86.exe REM remove leading :: to install Redistributable for x86 ::vc_redist.x64.exe REM remove leading :: to install Redistributable for x64 ::vc_redist.arm64.exe REM remove leading :: to install Redistributable for ARM64 mkdir "C:\Program Files\MyMFCApp" copy MyMFCApp.exe "C:\Program Files\MyMFCApp" ``` -------------------------------- ### Install and Start OpenSSH Server on Linux Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/linux/set-up-fips-compliant-secure-remote-linux-development.md Installs the OpenSSH server package and starts the SSH service on a Debian-based Linux system. Ensure the SSH server is running before proceeding with remote connections. ```bash sudo apt install openssh-server sudo service ssh start ``` -------------------------------- ### Example: Compiling and Linking with CL and _CL_ Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/build/reference/cl-environment-variables.md This example demonstrates setting both CL and _CL_ environment variables to compile source files and link object files. ```batch SET CL=FILE1.C FILE2.C \ SET \_CL\_=FILE3.OBJ \ CL ``` -------------------------------- ### Get Storyboard Start Keyframe - C++ Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/canimationcontroller-class.md Returns a keyframe that identifies the start of a storyboard. Obtain this keyframe to base other keyframes or transitions on the storyboard's start time. ```cpp static CBaseKeyFrame* GetKeyframeStoryboardStart(); ``` -------------------------------- ### ShowWindow Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/atl/reference/cwindow-class.md Example demonstrating the use of CWindow::ShowWindow. ```cpp #include "atlbase.h" #include "atlwin.h" void ShowMyWindow(_In_ HWND hWnd, _In_ int nCmdShow) { CWindow wnd(hWnd); // Set the show state of the window wnd.ShowWindow(nCmdShow); } ``` -------------------------------- ### CSettingsStore Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/csettingsstore-class.md Demonstrates the usage of CSettingsStore::Open and CSettingsStore::Read methods. ```APIDOC ## Example The following example demonstrates how to use the Open and Read methods of the `CSettingsStore` class. This code snippet is part of the [Tool Tip Demo sample](../../overview/visual-cpp-samples.md). [!code-cpp[NVC_MFC_ToolTipDemo#1](../../mfc/reference/codesnippet/cpp/csettingsstore-class_1.cpp)] ``` -------------------------------- ### Get gslice Start Index in C++ valarray Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/gslice-class.md Use the start() method to retrieve the starting index of a gslice within the original valarray. This is essential for understanding where the slice begins. ```cpp // gslice_start.cpp // compile with: /EHsc #include #include int main( ) { using namespace std; int i; valarray va ( 20 ), vaResult; for (i = 0 ; i < 20 ; i+=1 ) va [ i ] = i; cout << "The operand valarray va is:\n ( "; for ( i = 0 ; i < 20 ; i++ ) cout << va [ i ] << " "; cout << ")." << endl; valarray Len ( 2 ), Stride ( 2 ); Len [0] = 4; Len [1] = 4; Stride [0] = 7; Stride [1] = 4; gslice vaGSlice ( 0, Len, Stride ); vaResult = va [ vaGSlice ]; size_t vaGSstart = vaGSlice.start ( ); cout << "The valarray for vaGSlice is vaResult:" << "\n va[vaGSlice] = ( "; for (i = 0 ; i < 8 ; i++ ) cout << vaResult [ i ] << " "; cout << ")." << endl; cout << "The index of the first element of vaResult is: " << vaGSstart << "." << endl; } ``` -------------------------------- ### Complete Background Thread Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/cppcx/wrl/how-to-complete-asynchronous-operations-using-wrl.md A full example demonstrating the complete workflow for running an asynchronous operation in WRL. ```cpp #include #include #include #include #include using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; using namespace ABI::Windows::Foundation; using namespace ABI::Windows::System::Threading; // The work item to run on the background thread. void WorkItem(IAsyncAction* operation) { wprintf_s(L"Working...\n"); } int wmain() { // Initialize the Windows Runtime. RoInitializeWrapper initialize(RO_INIT_MULTITHREADED); if (FAILED(initialize)) { return -1; } // Create an activation factory for the IThreadPoolStatics interface. ComPtr threadPool; HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(), &threadPool); if (FAILED(hr)) { return -1; } // Create an Event object that synchronizes completion of the worker thread to the main app. Event event(CreateEvent(nullptr, FALSE, FALSE, nullptr)); // Call the IThreadPoolStatics::RunAsync method to create a worker thread. hr = threadPool->RunAsync(Callback([&event](IAsyncAction* operation) -> HRESULT { WorkItem(operation); // Set the event to signal that the work is complete. SetEvent(event.Get()); return S_OK; }).Get()); if (FAILED(hr)) { return -1; } // Print a message to the console and wait for the thread to complete. wprintf_s(L"Waiting for work to complete...\n"); WaitForSingleObject(event.Get(), INFINITE); wprintf_s(L"Work complete.\n"); } ``` -------------------------------- ### match_results::position Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/match-results-class.md Gets the starting offset of a subgroup. ```APIDOC ## match_results::position ### Description Returns the distance from the first character in the target sequence to the first character in the submatch. ### Parameters #### Query Parameters - **sub** (size_type) - Optional - Index of the submatch (defaults to 0). ``` -------------------------------- ### Example Usage of CSettingsStore::Open and CSettingsStore::Read Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/csettingsstore-class.md Demonstrates how to open a registry key and read a value using CSettingsStore. This is part of the Tool Tip Demo sample. ```cpp #include "afxsettingsstore.h" void CToolTipDemoView::OnSettingsChange() { CSettingsStore reg; CString str; // Try to read the value from the registry. if (reg.Read(_T("Software\MyCompany\MyProgram\Settings"), str)) { // If the value is read successfully, update the tooltip text. UpdateTooltipText(str); } else { // If the value is not found, use a default value. UpdateTooltipText(_T("Default Tooltip Text")); } } ``` -------------------------------- ### CObArray::InsertAt Example (Array) Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cobarray-class.md This example demonstrates inserting all elements from another CObArray into the current array starting at a specified index. The CAge class is defined in the CObList::CObList example. ```cpp #include "pch.h" #include "mfc.h" #include "mfcdoc.h" // The following example is used with CObArray::InsertAt and CObArray::operator[]. void CObArrayEx::InsertAtEx2() { CObArray arr; arr.Add( new CAge( 21, 30 ) ); arr.Add( new CAge( 40, 50 ) ); arr.Add( new CAge( 17, 25 ) ); CObArray arr2; arr2.Add( new CAge( 5, 10 ) ); arr2.Add( new CAge( 55, 60 ) ); // Insert all elements from arr2 into arr, starting at index 1. // The existing element at index 1 and all subsequent elements are shifted up. arr.InsertAt( 1, &arr2 ); // Delete the objects created with new. // Note that the elements in arr2 are not deleted, as they are owned by arr. arr.RemoveAll(); } ``` -------------------------------- ### begin, cbegin Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/tzdb-list-class.md Gets an iterator that points to the start of the `tzdb_list`. ```APIDOC ## `begin`, `cbegin` Gets an iterator that points to the start of the list. ```cpp const_iterator begin() const noexcept; // C++20 const_iterator cbegin() const noexcept; // C++20 ``` ### Return value An iterator pointing to the first `tzdb` in the list. ``` -------------------------------- ### Example of shared_ptr get() usage Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/shared-ptr-class.md Illustrates the usage of the get() member function to retrieve the pointer to the managed resource and check for null pointers. ```cpp // std__memory__shared_ptr_get.cpp // compile with: /EHsc #include #include int main() { std::shared_ptr sp0; std::shared_ptr sp1(new int(5)); std::cout << "sp0.get() == 0 == " << std::boolalpha << (sp0.get() == 0) << std::endl; std::cout << "*sp1.get() == " << *sp1.get() << std::endl; return (0); } ``` -------------------------------- ### Create and open a file with read/write permissions Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/opening-files.md Example demonstrating file creation with read/write access and exception handling using the TRACE macro. ```cpp CFile myFile; CFileException ex; if( !myFile.Open( _T("C:\\test\\example.dat"), CFile::modeCreate | CFile::modeReadWrite, &ex ) ) { TRACE( _T("Can't open file %s, error = %d\n"), ex.m_strFileName, ex.m_cause ); } ``` -------------------------------- ### BringWindowToTop Usage Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cwnd-class.md Demonstrates bringing a window to the top of the stack. ```cpp // NVC_MFCWindowing#71 // Note: The actual content of this snippet is retrieved from the referenced file. ``` -------------------------------- ### Reading Input with gets Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/c-runtime-library/gets-getws.md Example demonstrating the use of gets to read a line from stdin. Note that this usage is unsafe as it does not limit input length. ```c // crt_gets.c // compile with: /WX /W3 #include int main( void ) { char line[21]; // room for 20 chars + '\0' gets( line ); // C4996 // Danger: No way to limit input to 20 chars. // Consider using gets_s instead. printf( "The line entered was: %s\n", line ); } ``` -------------------------------- ### EnableWindow Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cwnd-class.md Example usage of the EnableWindow function. ```cpp [!code-cpp[NVC_MFCWindowing#93](../../mfc/reference/codesnippet/cpp/cwnd-class_32.cpp)] ``` -------------------------------- ### C++ auto_ptr get() Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/auto-ptr-class.md Demonstrates the usage of auto_ptr's get() and release() methods, showing how to obtain the raw pointer and release ownership. ```cpp // auto_ptr_get.cpp // compile with: /EHsc #include #include #include using namespace std; class Int { public: Int(int i) { x = i; cout << "Constructing " << ( void* )this << " Value: " << x << endl; } ~Int( ) { cout << "Destructing " << ( void* )this << " Value: " << x << endl; } int x; }; int main( ) { auto_ptr pi ( new Int( 5 ) ); pi.reset( new Int( 6 ) ); Int* pi2 = pi.get ( ); Int* pi3 = pi.release ( ); if (pi2 == pi3) cout << "pi2 == pi3" << endl; delete pi3; } ``` -------------------------------- ### Get GUID of a Library Block with __LIBID_ Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/cpp/uuidof-operator.md Use __LIBID_ as a substitute for __uuidof when the library name is out of scope. This is an alternative for retrieving the GUID of a library block. ```cpp StringFromCLSID(__LIBID_, &lpolestr); ``` -------------------------------- ### Output for _getch example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/c-runtime-library/reference/getch-getwch.md Expected console output after running the example. ```text Type 'Y' when finished typing keys: Y ``` -------------------------------- ### Example Header File Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/ide/include-cleanup-overview.md This is an example header file that includes standard library headers. ```cpp // myHeader.h #include #include void myFunc() { std::string s = "myFunc()\n"; std::cout << s; } ``` -------------------------------- ### Get new handler function Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/new-functions.md Retrieves the currently installed new_handler. ```cpp new_handler get_new_handler() noexcept; ``` -------------------------------- ### Custom Attribute Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/windows/attributes/module-cpp.md The 'custom' parameter allows for specifying one or more custom attributes, identified by their GUID. This example shows how to apply two custom attributes. ```cpp [module(custom={guid,1}, custom={guid1,2})]; ``` -------------------------------- ### Example header-units.json configuration Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/build/reference/header-unit-json-reference.md A sample configuration file listing files to be built as header units. ```json { "Version": "1.0", "BuildAsHeaderUnits": [ // macros.h should not be listed "a.h", "b.h" ] } ``` -------------------------------- ### Install x64 Redistributable via Command Line Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/windows/redistributing-visual-cpp-files.md Executes the x64 redistributable installer with passive progress tracking and suppresses automatic restarts. ```cmd vc_redist.x64.exe /install /passive /norestart ``` -------------------------------- ### Get Fill Style Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/atl/reference/cstockpropimpl-class.md Call this method to get the control's fill style, for example, solid, transparent, or crosshatched. The fill style is returned as a LONG. ```cpp HRESULT STDMETHODCALLTYPE get_FillStyle(LONG* pnFillStyle); ``` -------------------------------- ### BSCMAKE Example Build Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/build/reference/bscmake-command-line.md An example of how to run BSCMAKE to build a .bsc file from multiple .sbr files. ```APIDOC ## BSCMAKE Example Build ### Description This example demonstrates how to use BSCMAKE to create a browse information file named `MAIN.bsc` from three source browse files: `main.sbr`, `file1.sbr`, and `file2.sbr`. ### Method N/A (Command Line Tool) ### Endpoint N/A (Command Line Tool) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ``` BSCMAKE main.sbr file1.sbr file2.sbr ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Get Drawing Style Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/atl/reference/cstockpropimpl-class.md Call this method to get the control's drawing style, for example, solid, dashed, or dotted. The drawing style is returned as a LONG. ```cpp HRESULT STDMETHODCALLTYPE get_DrawStyle(LONG* pnDrawStyle); ``` -------------------------------- ### ShowCaret Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/atl/reference/cwindow-class.md Example demonstrating the use of CWindow::ShowCaret. ```cpp #include "atlbase.h" #include "atlwin.h" void ShowMyCaret(_In_ HWND hWnd) { CWindow wnd(hWnd); // Show the caret in the specified window wnd.ShowCaret(); } ``` -------------------------------- ### Get Activity Start Timestamp Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/build-insights/reference/sdk/cpp-event-data-types/activity.md Returns a tick value representing the exact moment an activity began. This is a raw timestamp for tracking activity start times. ```cpp const long long& StartTimestamp() const; ``` -------------------------------- ### Install SSH Server on Linux Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/linux/remote-file-explorer.md Install and start the SSH server on a remote Linux machine. Ensure the SSH service is running before connecting from Visual Studio. ```bash sudo apt update sudo apt install openssh-server sudo systemctl start ssh sudo systemctl status ssh ``` -------------------------------- ### CFile::SeekToBegin Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cfile-class.md Demonstrates resetting the file pointer to the start of the file. ```cpp [!code-cpp[NVC_MFCFiles#9](../../atl-mfc-shared/reference/codesnippet/cpp/cfile-class_14.cpp)] ``` -------------------------------- ### Create and remove a directory using _mkdir Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/c-runtime-library/reference/mkdir-wmkdir.md Demonstrates creating a directory with _mkdir and removing it with _rmdir. ```C // crt_makedir.c #include #include #include int main( void ) { if( _mkdir( "\\testtmp" ) == 0 ) { printf( "Directory '\\testtmp' was successfully created\n" ); system( "dir \\testtmp" ); if( _rmdir( "\\testtmp" ) == 0 ) printf( "Directory '\\testtmp' was successfully removed\n" ); else printf( "Problem removing directory '\\testtmp'\n" ); } else printf( "Problem creating directory '\\testtmp'\n" ); } ``` -------------------------------- ### Sample output for mbsinit example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/c-runtime-library/reference/mbsinit.md The expected output when running the provided example code. ```Output Locale set to: "Japanese_Japan.932" Currently in middle of mb conversion, state = 9a Currently in middle of mb conversion, state = e0 Currently in middle of mb conversion, state = f0 Conversion succeeded! MB String: AaBbCcxXyYzZ WC String: AaBbCcxXyYzZ ``` -------------------------------- ### Get Drawing Mode Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/atl/reference/cstockpropimpl-class.md Call this method to get the control's drawing mode, for example, XOR Pen or Invert Colors. The drawing mode is returned as a LONG. ```cpp HRESULT STDMETHODCALLTYPE get_DrawMode(LONG* pnDrawMode); ``` -------------------------------- ### Locate the msclr directory Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/dotnet/overview-of-marshaling-in-cpp.md Example path for the msclr directory in a Visual Studio installation. ```cmd C:\\Program Files (x86)\\Microsoft Visual Studio\\Preview\\Enterprise\\VC\\Tools\\MSVC\\14.15.26528\\include\\msclr ``` -------------------------------- ### Sample output for _utime example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/c-runtime-library/reference/utime-utime32-utime64-wutime-wutime32-wutime64.md Displays the expected console output after running the _utime demonstration program. ```Output Volume in drive C has no label. Volume Serial Number is 9CAC-DE74 Directory of C:\test 01/09/2003 05:38 PM 935 crt_utime.c 1 File(s) 935 bytes 0 Dir(s) 20,742,955,008 bytes free File time modified Volume in drive C has no label. Volume Serial Number is 9CAC-DE74 Directory of C:\test 01/15/2002 12:00 PM 935 crt_utime.c 1 File(s) 935 bytes 0 Dir(s) 20,742,955,008 bytes free ``` -------------------------------- ### Building and debugging the allocation-size-too-big example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/sanitizers/error-allocation-size-too-big.md Commands to compile the example with Address Sanitizer enabled and launch it in the debugger. ```cmd cl example1.cpp /fsanitize=address /Zi devenv /debugexe example1.exe ``` -------------------------------- ### Example: get a `local_info` Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/local-info-struct.md Demonstrates how to obtain and display `local_info` for the current system time. ```APIDOC ## Example: get a `local_info` ### Description This example shows how to retrieve `local_info` for the current local time and print it to the console. ### Code ```cpp // compile using: /std:c++latest #include #include using namespace std::chrono; int main() { const auto& timeZoneDatabase = get_tzdb(); const auto& currentZone = timeZoneDatabase.current_zone(); local_time lt = currentZone->to_local(system_clock::now()); auto localInfo = currentZone->get_info(lt); std::cout << "local_time: " << lt << "\n"; std::cout << localInfo << "\n"; return 0; } ``` ### Output Example ```output local_time: 2021-09-08 15:37:57.6853963 result: unique, first: (begin: 2021-03-14 10:00:00, end: 2021-11-07 09:00:00, offset: -25200s, save: 60min, abbrev: PDT) ``` ``` -------------------------------- ### Allocator size_type example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/allocator-class.md Demonstrates how to use size_type to get the maximum allocation size. ```cpp // allocator_size_type.cpp // compile with: /EHsc #include #include #include using namespace std; int main( ) { vector v; vector ::iterator vIter; vector :: allocator_type vAlloc; int j; for ( j = 1 ; j <= 7 ; j++ ) { v.push_back( 100.0 * j ); } cout << "The original vector v is:\n ( " ; for ( vIter = v.begin( ) ) ; vIter != v.end( ) ; vIter++ ) cout << *vIter << " " ; cout << " )." << endl; allocator::size_type vsize; vsize = vAlloc.max_size( ); cout << "The number of doubles that can be allocated before\n" << " the free memory in the vector v is used up is: " << vsize << "." << endl; } ``` -------------------------------- ### Get input buffer start pointer Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/basic-streambuf-class.md Returns a pointer to the beginning of the input buffer. ```cpp char_type *eback() const; ``` -------------------------------- ### Create and Split Path with _makepath_s and _splitpath_s Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/c-runtime-library/reference/makepath-s-wmakepath-s.md This C example demonstrates how to construct a full path using `_makepath_s` and then parse it back into its components (drive, directory, filename, extension) using `_splitpath_s`. Ensure the buffer size is sufficient for the combined path. ```C #include #include int main( void ) { char path_buffer[_MAX_PATH]; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; errno_t err; err = _makepath_s( path_buffer, _MAX_PATH, "c", "\sample\crt\", "crt_makepath_s", "c" ); if (err != 0) { printf("Error creating path. Error code %d.\n", err); exit(1); } printf( "Path created with _makepath_s: %s\n\n", path_buffer ); err = _splitpath_s( path_buffer, drive, _MAX_DRIVE, dir, _MAX_DIR, fname, _MAX_FNAME, ext, _MAX_EXT ); if (err != 0) { printf("Error splitting the path. Error code %d.\n", err); exit(1); } printf( "Path extracted with _splitpath_s:\n" ); printf( " Drive: %s\n", drive ); printf( " Dir: %s\n", dir ); printf( " Filename: %s\n", fname ); printf( " Ext: %s\n", ext ); } ``` ```Output Path created with _makepath_s: c:\sample\crt\crt_makepath_s.c Path extracted with _splitpath_s: Drive: c: Dir: \sample\crt\ Filename: crt_makepath_s Ext: .c ``` -------------------------------- ### CRichEditCtrl::GetSel Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cricheditctrl-class.md Gets the starting and ending positions of the current selection in this CRichEditCtrl object. ```APIDOC ## CRichEditCtrl::GetSel ### Description Gets the starting and ending positions of the current selection in this `CRichEditCtrl` object. ### Method (Not specified, likely a member function call) ### Endpoint N/A (Class member function) ### Parameters #### Path Parameters - **pnStart** (int*) - Output - Pointer to an integer that will receive the starting position of the selection. - **pnEnd** (int*) - Output - Pointer to an integer that will receive the ending position of the selection. ### Request Example ```cpp int start, end; richEditCtrl.GetSel(&start, &end); ``` ### Response #### Success Response (Boolean) - **Return Value** (BOOL) - Nonzero if the selection positions were retrieved successfully; otherwise 0. ### Response Example ```cpp // Example return value TRUE ``` ``` -------------------------------- ### Enable Tool Tips Example (C++) Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cwnd-class.md Example demonstrating how to enable tool tips for a window. This snippet is part of a larger example for CWnd::EnableToolTips. ```cpp [!code-cpp[NVC_MFCWindowing#91](../../mfc/reference/codesnippet/cpp/cwnd-class_30.cpp)] ``` ```cpp [!code-cpp[NVC_MFCWindowing#92](../../mfc/reference/codesnippet/cpp/cwnd-class_31.cpp)] ``` -------------------------------- ### Create CSettingsStore Instance Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/csettingsstoresp-class.md Demonstrates the usage of the Create method to instantiate a CSettingsStore object. ```cpp CSettingsStoreSP::Create(FALSE, FALSE); ``` -------------------------------- ### Get beginning of collection Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/atl/reference/ccomdynamicunkarray-class.md Returns a pointer to the start of the IUnknown interface pointer collection. ```cpp IUnknown** begin(); ``` -------------------------------- ### Create Analyzer Group Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/build-insights/reference/sdk/overview.md This example demonstrates how to create an analyzer group that prints 'Hello, world!' for every activity start event. It uses C++ interfaces and the `MakeStaticAnalyzerGroup` function. ```cpp using namespace Microsoft::Cpp::BuildInsights; class Hello : public IAnalyzer { public: AnalysisControl OnStartActivity( const EventStack& eventStack) override { std::cout << "Hello, " << std::endl; return AnalysisControl::CONTINUE; } }; class World : public IAnalyzer { public: AnalysisControl OnStartActivity( const EventStack& eventStack) override { std::cout << "world!" << std::endl; return AnalysisControl::CONTINUE; } }; int main() { Hello hello; World world; // Let's make Hello the first analyzer in the group // so that it receives events and prints "Hello, " // first. auto group = MakeStaticAnalyzerGroup(&hello, &world); unsigned numberOfAnalysisPasses = 1; // Calling this function initiates the analysis and // forwards all events from "inputTrace.etl" to my analyzer // group. Analyze("inputTrace.etl", numberOfAnalysisPasses, group); return 0; } ``` -------------------------------- ### Input file content for _futime example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/c-runtime-library/reference/futime-futime32-futime64.md Sample content for the input file used in the _futime demonstration. ```Input Arbitrary file contents. ``` -------------------------------- ### Get Limit Text Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cricheditctrl-class.md Retrieves the current text limit for the rich edit control. ```cpp void CMyRichEditCtrl::OnGetLimitText() { long nLimit = GetLimitText(); TRACE(_T("Text limit is %ld\n"), nLimit); } ``` -------------------------------- ### Get Compiler Help Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/build/walkthrough-compile-a-c-program-on-the-command-line.md Run `cl /?` in the developer command prompt for a quick list of available compiler options. ```bash cl /? ``` -------------------------------- ### Build DLL with command files Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/build/reference/linking.md Example of building a DLL by passing object files, libraries, and options via separate command files. Ensure command files do not exceed MAX_PATH (260 characters). ```cmd link /dll @objlist.txt @liblist.txt @exports.txt ``` -------------------------------- ### Get First Visible Line Example Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cricheditctrl-class.md Retrieves the index of the topmost visible line in the control. ```cpp void CMyRichEditCtrl::OnGetFirstVisibleLine() { int nLine = GetFirstVisibleLine(); TRACE(_T("First visible line is %d\n"), nLine); } ``` -------------------------------- ### std::crbegin Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/iterator-functions.md Gets a reverse read-only iterator to the elements of the container, starting at the end of the container. ```APIDOC ## std::crbegin ### Description Gets a reverse read-only iterator to the elements of the container, starting at the end of the container. ### Method Template function ### Endpoint N/A (Standard Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp template constexpr auto crbegin(const C& c) -> decltype(std::rbegin(c)); ``` ### Response #### Success Response (Reverse Const Iterator) - Returns a reverse const_iterator to the last element of the container. #### Response Example ```cpp std::vector v = {1, 2, 3}; auto crit = std::crbegin(v); // crit points to 3 ``` ``` -------------------------------- ### Example of OnShowMDITabContextMenu Implementation Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/mfc/reference/cmdiframewndex-class.md This example demonstrates how OnShowMDITabContextMenu can be implemented in the VisualStudioDemo sample. ```cpp #define AFX_MDI_CREATE_VERT_GROUP 0x0001 #define AFX_MDI_CREATE_HORZ_GROUP 0x0002 #define AFX_MDI_CAN_MOVE_PREV 0x0004 #define AFX_MDI_CAN_MOVE_NEXT 0x0008 #define AFX_MDI_CAN_BE_DOCKED 0x0010 BOOL CMainFrame::OnShowMDITabContextMenu(CPoint point, DWORD dwAllowedItems, BOOL bTabDrop) { // Enable the "New Vertical Tab Group" command if the user can create a vertical tab group: BOOL bShowVert = (dwAllowedItems & AFX_MDI_CREATE_VERT_GROUP); GetMenu()->EnableMenuItem(ID_NEW_VERT_GROUP, MF_BYCOMMAND | (bShowVert ? MF_ENABLED : MF_GRAYED)); // Enable the "New Horizontal Tab Group" command if the user can create a horizontal tab group: BOOL bShowHorz = (dwAllowedItems & AFX_MDI_CREATE_HORZ_GROUP); GetMenu()->EnableMenuItem(ID_NEW_HORZ_GROUP, MF_BYCOMMAND | (bShowHorz ? MF_ENABLED : MF_GRAYED)); // Enable the "Move Tab to Next Group" command if the user can move the tab to the next group: BOOL bShowNext = (dwAllowedItems & AFX_MDI_CAN_MOVE_NEXT); GetMenu()->EnableMenuItem(ID_MOVE_TAB_NEXT_GROUP, MF_BYCOMMAND | (bShowNext ? MF_ENABLED : MF_GRAYED)); // Enable the "Move Tab to Previous Group" command if the user can move the tab to the previous group: BOOL bShowPrev = (dwAllowedItems & AFX_MDI_CAN_MOVE_PREV); GetMenu()->EnableMenuItem(ID_MOVE_TAB_PREV_GROUP, MF_BYCOMMAND | (bShowPrev ? MF_ENABLED : MF_GRAYED)); // Enable the "Dock Tab" command if the user can dock the tab: BOOL bShowDock = (dwAllowedItems & AFX_MDI_CAN_BE_DOCKED); GetMenu()->EnableMenuItem(ID_DOCK_TAB, MF_BYCOMMAND | (bShowDock ? MF_ENABLED : MF_GRAYED)); // Display the shortcut menu: CMenu menu; if(menu.LoadMenu(IDR_POPUP_MDITABS)) // Example menu resource { CMenu* pPopup = menu.GetSubMenu(0); if(pPopup != NULL) { // Display the menu at the specified point pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this); return TRUE; } } return FALSE; } ``` -------------------------------- ### Get reverse iterator to start Source: https://github.com/microsoftdocs/cpp-docs/blob/main/docs/standard-library/basic-string-view-class.md Returns a const iterator to the first element in a reversed basic_string_view. ```cpp constexpr const_reverse_iterator rbegin() const noexcept; ```