Archive

Posts Tagged ‘Code Snippets C++’

Illustrating C++17 though code examples

March 29th, 2017 Comments off

Descriptions of C++17 features, presented mostly in “Tony Tables”.

There are actually over 100 changes in C++17, only some of them are listed here.

Caveat1: C++17 is completed, but not signed off yet. There may still be changes, although highly unlikely (modulo defects).

Caveat2: I make mistakes. This is more likely.

GitHub

std::tie

April 15th, 2015 No comments
struct S { A a; B b; C c; };
auto const S_fields = [](S const& obj) -> auto { return std::tie(obj.a, obj.b, obj.c); };
bool operator == (S const& lhs, S const& rhs) { return S_fields(lhs) == S_fields(rhs); }
bool operator < (S const& lhs, S const& rhs) { return S_fields(lhs) < S_fields(rhs); }

Complex initialization for a const variable

April 13th, 2013 No comments
int main()
{
    bool someFlag = false;
    const auto value = [&]{
                               if(someFlag)
                                   return -1;
                               else
                                   return 1;
                              } ();

    std::cout << "value == " << value << std::endl;
    return 0;
}

Complex initialization for a const variable

Clean memory

February 20th, 2012 No comments
// Swaps the process out of physical RAM memory
SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T)-1, (SIZE_T)-1);

Можно ещё делать так, когда память процесса превышает некую “норму”:

EmptyWorkingSet(GetCurrentProcess());

pragma warning

February 3rd, 2012 No comments

#pragma warning – enables selective modification of the behavior of compiler warning messages.

Additional “pragma warning” parameter is suppress – pushes the current state of the pragma on the stack, disables the specified warning for the next line, and then pops the warning stack so that the pragma state is reset.

Also __pragma() can be used instead of #pragma which allows it to use inside macros:

#define __const_cond( c ) \
 __pragma(warning(push)) \
 __pragma(warning(disable:4127)) \
 ( c ) \
 __pragma(warning(pop))

Windows common controls demo

December 27th, 2011 No comments

CppWindowsCommonControls contains simple examples of how to create common controls defined in comctl32.dll. The controls include Animation, ComboBoxEx, Updown, Header, MonthCal, DateTimePick, ListView, TreeView, Tab, Tooltip, IP Address, Statusbar, Progress Bar, Toolbar, Trackbar, and SysLink.

HexToInt

March 5th, 2011 No comments

Several implementations of HexToInt function:

1. This implementation was in Chrome

inline unsigned char HexToInt(unsigned char c)
{
DCHECK(IsHexDigit(c));
static unsigned char kOffset[4] = {0, 0x30u, 0x37u, 0x57u};
return c - kOffset[(c >> 5) & 3];
}

2. From SQLite

return (c + 9 * (1 & (c >> 6))) & 15;

3. another version

return c - (0x57373000 >> (c >> 5) * 8);

or

return c - (0x57373000 >> ((c >> 5) << 3));

4.  nobody will understand

return c - 128 + (c >> 5 & 3)["(PI)"];

or

return c - 128 + "(PI)"[(c >>5) & 3]

Fast memory copy (SSE4)

January 29th, 2011 No comments

Visual Studio 2008 has supports “Enable Instruction Functions” options (see a project settings -> C/C++ -> Optimization). Note that this option can enlarge code.

Also memcpy function implementation has written with using sse2 (movdqa).

int CopyMemSSE4(int* piDst, int* piSrc, unsigned long SizeInBytes)
{
// Initialize pointers to start of the USWC memory

_asm
{
mov esi, piSrc
mov edx, piSrc

// Initialize pointer to end of the USWC memory
add edx, SizeInBytes

// Initialize pointer to start of the cacheable WB buffer
mov edi, piDst

// Start of Bulk Load loop
inner_start:
// Load data from USWC Memory using Streaming Load
MOVNTDQA xmm0, xmmword ptr [esi]
MOVNTDQA xmm1, xmmword ptr [esi+16]
MOVNTDQA xmm2, xmmword ptr [esi+32]
MOVNTDQA xmm3, xmmword ptr [esi+48]

// Copy data to buffer
MOVDQA xmmword ptr [edi], xmm0
MOVDQA xmmword ptr [edi+16], xmm1
MOVDQA xmmword ptr [edi+32], xmm2
MOVDQA xmmword ptr [edi+48], xmm3

// Increment pointers by cache line size and test for end of loop
add esi, 040h
add edi, 040h
cmp esi, edx
jne inner_start
}
// End of Bulk Load loop

return 0;
}

#define DATA_SIZE 0x01000000

int main(int argc, char* argv[])
{
int *piSrc = NULL;
int *piDst = NULL;
unsigned long dwDataSizeInBytes = sizeof(int) * DATA_SIZE;

piSrc = (int *)_aligned_malloc(dwDataSizeInBytes, dwDataSizeInBytes);
piDst = (int *)_aligned_malloc(dwDataSizeInBytes, dwDataSizeInBytes);

memset(piSrc, 255, dwDataSizeInBytes);
memset(piDst, 0, dwDataSizeInBytes);

CopyMemSSE4(piDst, piSrc, dwDataSizeInBytes);

_aligned_free(piSrc);
_aligned_free(piDst);
}

Additional links:

Is process a member of the Administrators local group

January 29th, 2011 No comments

The CheckTokenMembership function determines whether a specified security identifier (SID) is enabled in an access token.

/*
Routine Description: This routine returns TRUE if the caller's
process is a member of the Administrators local group. Caller is NOT
expected to be impersonating anyone and is expected to be able to
open its own process and process token.
Arguments: None.
Return Value:
TRUE - Caller has Administrators local group.
FALSE - Caller does not have Administrators local group.
*/
BOOL IsUserAdmin(void)
{
 BOOL bResult;
 SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
 PSID AdministratorsGroup;
 bResult = AllocateAndInitializeSid(&amp;NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
                                    DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
                                    &amp;AdministratorsGroup);
 if(bResult)
 {
  if(!CheckTokenMembership(NULL, AdministratorsGroup, &amp;bResult))
  {
   bResult = FALSE;
  }
  FreeSid(AdministratorsGroup);
 }
 return(bResult);
}

MSDN

QThread

June 18th, 2010 No comments

QThread was designed and is intended to be used as an interface or a control point to an operating system thread, not as a place to put code that you want to run in a thread. We object-oriented programmers subclass because we want to extend or specialize the base class functionality. The only valid reasons I can think of for subclassing QThread is to add functionality that QThread doesn’t have, e.g. perhaps providing a pointer to memory to use as the thread’s stack, or possibly adding real-time interfaces/support. Code to download a file, or to query a database, or to do any other kind of processing should not be added to a subclass of QThread; it should be encapsulated in an object of it’s own.

You’re doing it wrong…

// create the producer and consumer and plug them together
Producer producer;
Consumer consumer;

bool bOk = producer.connect(&amp;consumer,
                            SIGNAL(consumed()),
                            SLOT(produce()));
Q_ASSERT(bOk);
bOk = consumer.connect(&amp;producer,
                       SIGNAL(produced(QByteArray *)),
                       SLOT(consume(QByteArray *)));
Q_ASSERT(bOk);

// they both get their own thread
QThread producerThread;
producer.moveToThread(&amp;producerThread);

QThread consumerThread;
consumer.moveToThread(&amp;consumerThread);

// go!
producerThread.start();
consumerThread.start();

Reference: Threading without the headache or QThread’s no longer abstract (see attached file)