Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. int main( int argc, char * argv[] )
  2. {
  3.     argc; argv;
  4.  
  5. #ifdef _WIN64
  6.     printf( "_WIN64\n\n");
  7. #else
  8.     printf( "_WIN32\n\n");
  9. #endif
  10.  
  11.     {
  12.         PacketRef packet1 = NewPacket(); // Valid: Intended use, + 1 ref
  13.  
  14.         // PacketRef * ptr_ref = &packet1; // DANGEROUS: Can have a "dangling pointer" to an object that no longer exists.
  15.  
  16.         packet1->Write<uint16_t>( 0 ); // API example
  17.         packet1->Write<uint16_t>( 0x5000 );
  18.         packet1->Write<uint16_t>( 0 );
  19.         packet1->Write<uint8_t>( 1 );
  20.         packet1->Overwrite<uint16_t>( 0, (uint16_t)packet1->GetTotalBytes() - 6 ); // API example
  21.         packet1->Finalize(); // Required for further API use
  22.  
  23.         // void F( PacketRef packet )
  24.         F( packet1 ); // Valid: copy ctor'ing is ok, + 1 ref, then - 1 ref
  25.         // NOTE: The 'smart pointer' object is copied, actual data is always used via a pointer
  26.  
  27.         // void G( PacketRef & packet )
  28.         G( packet1 ); // Valid: Just a reference, no copying
  29.         // NOTE: susceptible to dangling reference issues noted below
  30.  
  31.         //PacketRef packet2; // Invalid: no appropriate default constructor available
  32.  
  33.         //packet1 = NewPacket(); // Valid: However, packet is freed since no more refs exist
  34.  
  35.         PacketRef packet3( packet1 ); // Valid: copy ctor'ing is 'ok', + 1 ref
  36.  
  37.         packet1 = NewPacket(); // Valid: since a ref exists, old packet is not freed
  38.  
  39.         // Valid: simply holding a normal reference to an object
  40.         PacketRef & packet4 = packet3;
  41.  
  42.         //packet3 = NewPacket(); // DANGEROUS: We now have a "dangling reference" to an object that no longer exists
  43.  
  44.         // Valid: Object still exists since packet3 has a ref to it
  45.         uint16_t packet_size = packet4->Read<uint16_t>(); // API use
  46.         uint16_t packet_opcode = packet4->Read<uint16_t>();
  47.         uint16_t packet_security = packet4->Read<uint16_t>();
  48.         printf( "[%.4X][%i bytes][%.4X]\n\n", packet_opcode, packet_size, packet_security );
  49.  
  50.     } // packet3 dtor, packet1 dtor since no more refs for either
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement