1, VC6 in the Min/max disaster
There are some small problems when using the Boost library in VC or other libraries.
The min and Max macros are already defined in the header file of Windows, so the two functions in the STL are not called, for example, in MFC, but in boost, it is the std:: function under the namespace, Functions that use Windows cannot accept different types of parameters for use in templates, but many libraries rely on them.
While boost tries to deal with these issues, sometimes it is necessary to include code like the following in your code to add a # define _nominmax before the first # include.
#define _NOMINMAX//disable windows.h defining min and Max as macros #include "BOOST/CONFIG.HPP"//include boosts compiler-specific "fixes" Using Std::min; Makle them globally available Using Std::max; |
This does not need to be done at any time, but we need to add this code only when we are using it.
2. String Lookup function performance
When searching for strings, the Boost library provides a boost::contains and Boost::icontains method, which ignores string case. However, when testing performance, these two functions have a huge impact on performance, and using the Find function string/wstring comes with a lot of performance improvements. Boost::icontain consumption performance of the main reasons to see the source code, found mainly in the internal make a number of is_equal () calls, and each time is_equal will be to_upper () or to_lower () operation. So it is recommended to use the string's own find when considering performance.
Resolver's asynchronous query (Async_resolve) took me 1 hours, although the tutorial said it was easy to use async_resolve based on the documentation, but it was actually written with a problem.
BUG: Error is always passed in when an asynchronous completion handle is called.
But from the Internet to check the information, the basic and I write the same ah, no difference. Finally, various attempts to find out the reasons for the inside.
Workaround: Io_service must be initialized after socket,resolver to invoke the run () function, or the asynchronous query always fails.
3. Any
This class provides functionality like shared_ptr: It can contain any type. But any is not a template class. So we can use it as a type parameter in the STL container, so that we can implement any type of object in the STL container. The any_cast in any is the essence of the need to access an instance of any to obtain a new instance copy.
4, operator
The operators header file contains a number of solutions that have the overloaded extension operator, as written in the book, if we provide operator<, then I should provide the operator<=,>=,> operator, but in fact we find that By opertor< we are able to launch operator<=,operator>=,operator> and other operators, but we tend to ignore or fear errors so that our class operator overloads are not "friendly" enough, Users cannot use the same as expected. The Opertors library allows these secondary operator overloads that rely on the main operator overloading to be simpler and more conceptualized and systematized. By deriving from Less_than_comparable<typename T>, we can achieve comparisons, and through other concepts, we will be simpler and clearer to implement the various operators that should be available.
5. Resolve __int64 errors caused by boost including BOOST/ALGORITHM/STRING.HPP
Cross-platform operations using the Boost string library, including files
#include <boost/algorithm/string.hpp>
Result encountered compilation error
Error C2632: ' __int64 ' followed by ' __int64 ' is illegal
Found in config-win32.h already defined macros, in BOOST\CSTDINT.HPP again using a typedef, workaround, increase the resolution, increase the #undefint64_t
#undef int64_t
#include <boost/algorithm/string.hpp>
6, solve the boost contains #include<boost/asio/ip/tcp.hpp> caused by "error C2632:" __int64 "Behind the" __int64 "illegal" error
Workaround, Increase #undefint64_t
#undefint64_t
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/array.hpp>
#include <boost/function.hpp>
7. Several points of attention using smart pointers
A smart pointer is a C + + object like a pointer, but it can be destroyed by itself when the object is not in use.
We know that objects in C + + are difficult to define because they are no longer used, so resource management in C + + is complex. Various smart pointers can operate in different situations. Of course, smart pointers can delete objects at the end of a task, except in a program.
Many libraries provide the operation of smart pointers, but all have their own advantages and disadvantages. The boost library is a high-quality, open-source C + + Template Library that many people consider adding to the next version of the C + + standard library.
Boost defines the kind of smart pointers.
Shared_ptr<t> |
Internally maintains a reference counter to determine if this pointer needs to be freed. Is the most commonly used smart pointer in boost. |
Scoped_ptr<t> |
Automatically released when the scope of the pointer disappears |
Intrusive_ptr<t> |
Also maintains a reference counter, which has better performance than shared_ptr. But ask T to provide this counter yourself. |
Weak_ptr<t> |
Weak pointers, to be used in conjunction with shared_ptr |
Shared_array<t> |
is similar to shared_ptr, but accesses an array |
Scoped_array<t> |
is similar to Scoped_ptr, but accesses an array |
Here are a few places to be aware of using smart pointers:
When you declare a smart pointer, you instantiate it immediately, and you must not release it manually.
..._ptr<t> is not a t* type. So:
A: When declaring, ..._ptr<t> not ....._ptr<t*>.
B: You can't assign a t*-type pointer to it.
C: Can not write ptr=null, and use Ptr.reset () instead.
Cannot loop reference.
Do not declare a temporary SHARE_PTR, then pass this pointer to a function
Shared_ptr<t> usage Examples
#include <stdio.h>
#include <boost/shared_ptr.hpp>
class A {public
:
void print () {
printf ("Class A print!\n");
}
};
int main (int argc, char **argv) {
boost::shared_ptr<a> A1 (New A ());
A1->print ();
}
8. Get the object address
& is used as a fetch symbol to get the address of an object, but because C + + is too flexible, overloading operator& can change the original semantics of operator&. When you need to use the real address of the object, in this case the Boost library AddressOf function.
#include "stdafx.h"
#include <iostream>
#include <boost/utility.hpp>
usingnamespaceboost;
USINGNAMESPACESTD;
Classobject
{public
:
Object () {m_age =;}
intoperator& ()
{
return0;
}
Intgetage () {returnm_age;}
Protected:
intm_age;
};
Intmain ()
{
objectobj;
cout<<&obj<<endl;//output
Object *p=addressof (obj);
cout<<p<<endl;//Output obj Real address
cout<<p->getage () <<endl;
}
9, Boost::asio Async_write can not guarantee to send out all data at once
Read Basic_stream_socket's documentation, which mentions that Async_write_some cannot guarantee that all data sent will be emitted. And mention that if you want to do this, you need to use boost ASIO's async_write
Http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/basic_stream_socket/async_write_some.html
Async_write sometimes cannot send out data at the same time. So I had to write a recursive function to retry sending. It is also very simple to pass bind, each time passing the number of bytes you want to send to the log and sending the start position to the async callback function.
The code reference is as follows:
void Sign::afterwritemessage (Error_code const& ec,size_t bytes_transferred, size_t expected_size, size_t Offset) { if (EC) { booster_error ("afterwritemessage") << "Writemessage failed, ERROR code : "<< ec.value () << category name: << ec.category (). Name () << "id_:" << id_ << "Address:" <<address <<
"Message:" <<ec.message ();
Close ();
return; &nBsp } booster_debug ("Afterwritemessage") << "thread ID:" << this_thread::get_id () << "Send_ Buffer: "<< printbytesashexstring (Send_buffer, bytes_transferred) <<" Sent size: "<< bytes_
transferred; booster_debug ("Afterwritemessage") << "thread ID:" << this_thread::get_id () << "Send_buffer:"
<< printbytesashexstring (Send_buffer, expected_size) << "expected size:" << expected_size;
size_tresend_size = expected_size-bytes_transferred; if (resend_size> 0) { Size_tnew_offset = offset + bytes_transferred; async _write (socket, buffer (void*) &send_buffer[new_offset],resend_size),
Strand_.wrap (Bind (&sign::afterwritemessage,shared_from_this (), _1, _2, Resend_size, New_offset)));
return; } //do yourbusiness after send succeeds } void sign::SendMessage (size_t size) { // booster_debug ("SendMessage") << "thread ID:" << this_thread::get_
ID () << "Send_buffer:" << printbytesashexstring (send_buffer, size) << "size:" << size; async_write (socket, buffer (send_buffer, size), strand_.wrap
(Bind (&sign::afterwritemessage,shared_from_this (), _1, _2, size, 0))); }
10. Using Enable_shared_from_this
Inheriting the class allows for a secure weap_ptr-to-shared_ptr conversion based on the current subclass ...
Code instance
The Y class inherits enable_shared_from_this in the following code, so we can call shared_from_this directly in the function to get the object's shared_ptr
Class y:publicenable_shared_from_this<y>
{public
:
shared_ptr<y> F ()
{
re Turnshared_from_this ();
}
}
int main ()
{
shared_ptr<y> P (newy);
Call F to get shared_ptr
shared_ptr<y> q =p->f ();
ASSERT (P = = q);
ASSERT (! ( P < Q | | Q <p)); P and Q must share ownership
}
11. Boost Lock
Boost read-write lock, share-exclusive lock, when read-write lock is locked in the reading mode, it is locked in shared mode, when it is locked in write mode, it is locked in exclusive mode.
Typedefboost::shared_lock<boost::shared_mutex> Readlock;
typedef boost::unique_lock<boost::shared_mutex> Writelock;
Boost::shared_mutex Rwmutex;
void ReadOnly ()
{
Readlock Rdlock (Rwmutex);
Do something
}
void WriteOnly ()
{
Writelock Wtlock (Rwmutex);
Do something
}
For the same Rwmutex, threads can have multiple readlock at the same time, and these readlock block any thread that attempts to acquire Writelock until all Readlock objects are refactored. If Writelock first obtains the Rwmutex, it blocks any thread that attempts to gain Readlock or Writelock on Rwmutex.
Mutual exclusion Lock
typedef boost::unique_lock<boost::mutex> Exclusivelock;
Recursive mutual-exclusion amount
The Boost::recursive_mutex provides a recursive mutex amount. For an instance to allow at most one thread to have its lock, if a thread has locked a Boost::recursive_mutex instance, the thread can lock the instance multiple times.
12, the difference between Async_read and async_read_some in Boost::asio
Asio::async_read usually the user reads the specified length of data and returns after reading or error. The socket's async_read_some reads the data or returns with an error, not necessarily reading the entire package.
void Async_read (asyncreadstream& s, constmutablebuffersequence& Buffers,readhandler handler) must wait until the buffer is filled, Otherwise, the Readhandler handle is not called even if the packet is received.
Boost::asio::async_read (M_socket,boost::asio::buffer (Recvdata,nneedrecvlen),
Boost::bind (&clientsession::handle_read,this,boost::asio::p laceholders::error));
boost::array<char,512>m_recvbuf;
Ip::tcp::socket M_socket;
Synchronous
Boost::system::error_codeerror;
Std::size_tnsize = M_socket.read_some (Boost::asio::buffer (M_RECVBUF), error);
Asynchronous
M_socket.async_read_some (Boost::asio::buffer (m_recvbuf),
boost::bind (&tcpconnection::handle_read, this ,
Boost::asio::p laceholders::error,
boost::asio::p laceholders::bytes_transferred));
The Sync_read_some function can only receive approximately 1k of data at a time, and it needs to be received repeatedly if it is to receive big data.
13. Each version of the Boost library download address
Boost Library official website: http://www.boost.org/
Download address for each version of the Boost library:
https://sourceforge.net/projects/boost/files/boost-binaries/