高春辉做了一个功德无量的事情,整理了一份高质量的 IP 库,http://tool.17mon.cn/ipdb.html,官方给出了 php 版本的解析函数,但是没有 c++ 的,倒是有人写了一个 php c 扩展,https://github.com/shukean/mon…,不过太长了。。
于是自己写了个 c++ 的
#include <stdio.h>
#include <stdlib.h>
#…… 阅读全文
Tag Archives: C++
fprintf 是线程安全的吗
以前一直担心在多线程环境下,多个线程同时调用 fprintf 往同一个 fp 写东西会不会出现交错的情况,昨天微博上问了问人,有提到 fprintf_unlocked,也说到 fprintf 是线程安全的,后来又查了一下,看到这里,http://stackoverflow.com/quest… ,其中也有提到,fprintf 在多线程下是内部持有锁的
If you’re …… 阅读全文
对 c++ unordered_map 源码的解析
主要尝试回答下面几个问题:
一般情况下,使用 hash 结构,需要有桶的概念,那么 unordered_map 是如何自动管理桶的,这个问题其实再细分的话是这样的:
初始的桶是如何设置的
当需要扩容的时候,是如何重新分布的
对于 string,unordered_map 的默认哈希函数是怎样的
代码位于 /usr/include/c++/4.1.2/tr1/,编译…… 阅读全文
tr1 的 unorderd_map
#include <tr1/unordered_map>
#include <stdio.h>
#include <string>
int main() {
typedef std::tr1::unordered_map<std::string, int> HashMap;
HashMap mapNumber;
mapNumber["one"] = 1;
mapNumber["two"] = 2;
std::tr1::hash<st…… 阅读全文
tr1 的 bind 和 function
首先来看两个文章,function/bind的救赎(上),http://blog.csdn.net/myan/arti…,以boost::function和boost:bind取代虚函数,http://blog.csdn.net/solstice/…,前者讲背景和理论,后者讲实际操作和细节对比,读来酣畅淋漓,醍醐灌顶
这么好的东西,当然要想着怎么在现有的环境条件下用起来,没有 boost,…… 阅读全文
对引用取地址
今天突然想到,如果我们对一个引用取地址,那么会怎么样呢,例如这样
#include <stdio.h>
class CNumber {
public:
int n;
};
void printByPointer(CNumber* pNumber) {
printf("%d\n", pNumber->n);
}
void printByRef(CNumber& oNumber) {
printf("%d\n", oNumb…… 阅读全文
tr1 memory 中的智能指针
tr1/memory 中带了一个 shared_ptr 的智能指针,也有配套的 weak_ptr,但是没有 scoped_ptr,不过起码可以不用等到 c++11 的编译器了
#include <tr1/memory>
#include <stdio.h>
class CTest {
public:
CTest() {
printf("CTest\n");
}
~CTes…… 阅读全文
函数返回对象时的问题
来看这个代码
#include <iostream>
#include <string>
#include <map>
std::map<std::string, std::string> mapHttpRequest;
std::string GetString(std::string strKey)
{
std::map<std::string, std::string>::iterator it = mapHttpRequest.find(strKey);
if (it…… 阅读全文
pthread_self 和 gettid 的性能区别
打日志的时候,我们希望把线程 id 打印出来,线程 id 有两个方法可以获取,gettid 和 pthread_self,前者是一个 Linux 的系统调用,后者是一个可移植的库函数,可移植性倒还好,因为也不怎么考虑跨平台,另外一个区别,就是他们的返回值不一样,这个可以看到这里,http://stackoverflow.com/quest…,有一个讨论,摘…… 阅读全文
基于队列的 UDP 多线程收发 demo
来看这个代码
#include <stdio.h>
#include <assert.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <string.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.…… 阅读全文