互斥锁 mutex

互斥锁

在多线程的情况下,当一个变量可以被多个线程修改时,就需要考虑多线程同步问题。线程A修改变量前,先加锁,修改结束再解锁,然后线程B获取同样的锁,修改结束再解锁,如果不是同一把锁,同步是无效的。

在C++中使用pthread的互斥量接口实现数据同步,线程A对互斥量mutex加锁后,其他尝试加锁的线程都会阻塞,等线程A解锁后,其他线程从阻塞变为运行态,第一个抢到CPU的线程加锁成功,其他线程再次阻塞,这样每次只有一个线程能加锁。这里存在规则统一的问题,就是线程可以在不加锁情况下访问变量,此时即使另一个线程加了锁,还是会出现不同步的问题,所以不能有的线程需要加锁,有的线程不需要加锁,必须统一化。

缺点:

  • 重复锁定和解锁,每次都会检查共享数据结构,浪费时间和资源;
  • 繁忙查询的效率非常低;

互斥锁的程序如下,注意两个线程的join是在两个线程定义之后运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<ros/ros.h>
#include <boost/thread.hpp>
#include "boost/thread/mutex.hpp"
using namespace std;

boost::mutex myLock;
unsigned sum = 10;

void thread_1(int n)
{
myLock.lock();
sum = sum * n;
sleep(2);
cout<<"thread 1, sum: "<< sum <<endl;
myLock.unlock();
}

void thread_2(int n)
{
sleep(1);
myLock.lock();
sum = sum * 7 * n;
cout<<"thread 2, sum: "<< sum <<endl;
myLock.unlock();
}

int main()
{
unsigned int n = 2;
boost::thread th_1 = boost::thread(boost::bind(&thread_1,n));
boost::thread th_2 = boost::thread(boost::bind(&thread_2,n));

th_1.join();
th_2.join();
return 0;
}

不加互斥锁的情况下,运行结果

调试时,我发现mutex的lockunlock应当包括cout,否则执行顺序还是不确定。

try_lock

解释一下try_lock的特点,它试图取得一个lock,成功就返回true, 失败就返回false. 但是失败也不会阻塞。

If try_lock is called by a thread that already owns the mutex, the behavior is undefined.

程序如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<ros/ros.h>
#include <boost/thread.hpp>
#include "boost/thread/mutex.hpp"
using namespace std;

boost::mutex myLock;
unsigned sum = 10;

void thread_1(int n)
{
cout << "start thread 1" << endl;
myLock.lock();
sum = sum * n;
cout<<"thread 1, sum: "<< sum <<endl;
// myLock.unlock();
}

void thread_2(int n)
{
cout << "start thread 2" << endl;
myLock.lock();
// myLock.try_lock();
sum = sum * 7 * n;
cout<<"thread 2, sum: "<< sum <<endl;
myLock.unlock();
}

int main()
{
unsigned int n = 2;
boost::thread th_1 = boost::thread(boost::bind(&thread_1, n) );
boost::thread th_2 = boost::thread(boost::bind(&thread_2, n) );

th_1.join();
th_2.join();
return 0;
}

运行结果是
1
2
3
start thread 1
thread 1, sum: 20
start thread 2

显然线程1的最后没有unlock互斥锁,线程2获取互斥锁失败,会阻塞。

如果在线程2中改用try_lock,就不会阻塞,运行结果是

1
2
3
4
start thread 1
thread 1, sum: 20
start thread 2
thread 2, sum: 280

或者
1
2
3
4
start thread 1start thread 2
thread 1, sum:
thread 2, sum: 280
20

是不会阻塞,但会出现我们不想要的结果。

参考: C++ 多线程互斥锁


Linux系统函数

exit函数

exit中的参数exit_code为0代表进程正常终止,若为其他值表示程序执行过程中有错误发生。出错时退出一般用exit(EXIT_FAILURE);

system()函数

这个函数是调用/bin/sh执行脚本的,有些命令如rosrun不能在/bin/sh下执行

WIFEXITED(status) 这个宏用来指出子进程是否为正常退出的,如果是,它会返回一个非零值。当WIFEXITED返回非零值时,我们可以用这个宏来提取子进程的返回值,如果子进程调用exit(5)退出,WEXITSTATUS(status)就会返回5;如果子进程调用exit(7),WEXITSTATUS(status)就会返回7。请注意,如果进程不是正常退出的,也就是说,WIFEXITED返回0,这个值就毫无意义。

所以一个典型的system函数的使用是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
pid_t status;
std::string cmd = "rosnode kill /lidar";
status = system(cmd.data());
if (-1 == status) // 语句有错
{
return -1;
}
else
{
ROS_INFO("WIFEXITED return: %d",WIFEXITED(status));
if (WIFEXITED(status)) //返回一个非零值, 正常退出
ROS_INFO("child process exit done: %d", WEXITSTATUS(status) );
else
ROS_INFO("child process exit abnormally");
}

errno

errno表示错误代码。 记录系统的最后一次错误代码。代码是一个int型的值,在errno.h中定义。系统每一次出错都会对应一个出错代码,例如12表示“Cannot allocate memory”。

stderr和fprintf函数

linux中的进程启动时,都会打开三个文件:标准输入、标准输出和标准出错处理。通常这三个文件都与终端联系。这三个文件分别对应文件描述符0、1、2。系队统自定义了三个文件指针stdin、stdout、stderr,分别指向标准输入、标准输出和标准出错输出。stderr是linux标准出错的文件指针,定义为extern struct _IO_FILE *stderr;,对应文件描述符2,通常结合fprintf使用:

1
fprintf(stderr,"error message");	//不必加换行

STDERR_FILENO和write函数

1
2
3
4
/* 文件描述符*/
#define STDIN_FILENO 0 /* Standard input. */
#define STDOUT_FILENO 1 /* Standard output. */
#define STDERR_FILENO 2 /* Standard error output. */

与上面用法类似,但write的首个参数是文件描述符:

1
2
char err[] = "error\n";
write(STDERR_FILENO,err,strlen(err)); //输出error(换行)

perror函数

需要包含头文件stdio.h,perror是错误输出函数,在标准输出设备上输出一个错误信息,是对errno的封装。perror(“fun”),其输出为:fun:后面跟着错误信息(加一个换行符)。

1
perror("status:");	//不报错时,输出 status:Success

strerror函数

stderror是通过参数errno,返回错误信息:printf("strerror: %s\n",strerror(errno));

atexit函数

功 能: 注册终止函数(即main执行结束后调用的函数)

用 法: int atexit(void (*func)(void)),也就是只能注册形参和返回值都为空的函数

exit函数和_exit函数都可以退出程序,但后者是立即进入内核,前者是做一些清理处理再进入内核.atexit函数就是用于执行清理时的一些操作.

exit调用终止处理函数的顺序和atexit登记的顺序相反.程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void  test1()
{
cout<<"test 1"<<endl;
}

void test2()
{
cout<<"test 2"<<endl;
}

void test3()
{
cout<<"test 3"<<endl;
}

int main()
{
atexit(test1);
atexit(test2);
atexit(test3);
return 0;
}

运行结果:
1
2
3
test 3
test 2
test 1

gethostname函数

功能是获得计算机主机名,形参分别是char*和字符长度,成功会返回0

1
2
3
4
char name[40];
memset(name,0,sizeof(name));
if(!gethostname(name,sizeof(name) ) )
printf("%s\n\n",name);


memset和memcpy函数

memset函数

原型:void *memset(void *s, int ch, size_t n);
作用:将s所指向的内存中的前n个字节的内容全部设置为ch指定的ASCII值,这个函数通常为新申请的内存做初始化工作。一般用于结构体和数组的初始化。

  1. memset中的第三个参数一定要使用sizeof操作符,因为每个系统下对类型长度的定义可能不一样。
  2. memset中的第一个参数一定要是一个已知的、已经被分配内存的地址,否则会出错。
  3. 对于单字节数据类型(char)可以初始化为任意支持的值,都没有问题,但是对于非多字节数据类型只能初始化为0,而不能初始化成别的初值,否则容易出错。

memset的效率很高,比手动赋值要高的多,比bzero也要高,尤其大数组的情况。

我是这样实现的:

1
2
3
4
5
6
7
8
9
10
11
void* _memset(void* dst,int val, size_t count)
{
assert(dst!=NULL);
char* tmpdst = (char*)dst;
while(count--)
{
*tmpdst = (char)val;
tmpdst++;
}
return dst;
}

memcpy函数

memcpy函数的使用场合是不需要考虑内存重叠问题的,因为涉及到内存重叠时我们应该调用的是memmove函数。我是这样实现的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void* _memcpy(void* dst, const void* src, size_t n)
{
assert(dst!=NULL && src!=NULL);
assert(n>=0);
char* temp = (char*)dst;
const char* p = (char*)src;
size_t m=0; //void指针不能自增
while(n--)
{
*temp = *p;
temp++;
p++;
}
return dst;
}

memmove进行了改进,考虑了内存重叠的情况:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void* my_memmove(void* dst, const void* src, size_t n)
{
char* s_dst;
char* s_src;
s_dst = (char*)dst;
s_src = (char*)src;
if(s_dst>s_src && (s_src+n>s_dst)) {
s_dst = s_dst+n-1;
s_src = s_src+n-1;
while(n--) {
*s_dst-- = *s_src--;
}
}else {
while(n--) {
*s_dst++ = *s_src++;
}
}
return dst;
}


shell命令 — 字符串相关

type -a 命令可以查看某个shell命令的含义,对alias也适用

echo带颜色的文本

需要使用参数-e,格式为echo -e "\033[字背景颜色;文字颜色m字符串\033[0m",比如"\033[45;5m 闪烁效果 \033[0m"

1
2
3
4
5
6
echo -e "\033[40;37m 黑底白字 \033[0m"
echo -e "\033[41;37m 红底白字 \033[0m"
echo -e "\033[42;37m 绿底白字 \033[0m"
echo -e "\033[43;37m 黄底白字 \033[0m"
echo -e "\033[44;37m 蓝底白字 \033[0m"
echo -e "\033[45;37m 紫底白字 \033[0m"

\033[5m 闪烁效果,这个以前不知道

1
2
3
4
5
6
7
8
9
字背景颜色范围: 40--49                   字颜色: 30--39 
40: 黑 30: 黑
41:红 31: 红
42:绿 32: 绿
43:黄 33: 黄
44:蓝 34: 蓝
45:紫 35: 紫
46:深绿 36: 深绿
47:白色 37: 白色

对shell脚本进行语法检查

1
bash -n script_name.sh         //   -n选项只做语法检查,而不执行脚本。

例如,检查结果可能是这样:

1
2
3
# bash -n t.sh 
t.sh: line 6: syntax error in conditional expression: unexpected token `;'
t.sh: line 6: syntax error near `;'

连续执行命令

连续执行shell命令有三种情况:

  • 用分号;间隔,会一直执行,无论命令对错。 echo abc; echo 123
  • &&间隔,执行到错误命令会停止。echo abc && adf && echo 123
  • ||间隔,执行到正确命令会停止。

二元比较操作符,比较变量或者比较数字.

整数比较

1
2
3
4
5
6
-eq 等于        if [ "$a" -eq "$b" ] 
-ne 不等于 if [ "$a" -ne "$b" ]
-gt 大于 if [ "$a" -gt "$b" ]
-ge 大于等于 if [ "$a" -ge "$b" ]
-lt 小于 if [ "$a" -lt "$b" ]
-le 小于等于 if [ "$a" -le "$b" ]

比如 $a -eq 10

字符串比较

1
2
= 等于        if [ "$a" = "$b" ] 
== 等于 if [ "$a" == "$b" ],与=等价


参考: shell脚本 if语句

字符串条件判断

1
2
3
4
if [ "$net" = "0" ]
then
echo "local"
fi

注意:

  • 左右方括号都要留空位,if后面也要有空位
  • Shell下使用等号赋值时,左右两边不能有空位
  • 一个等号和两个等号都可以
  • then要另起一行,以if开头,以fi结尾

查找字符串

grep -r "struct event_base" -n
在当前目录查找字符串,找到后返回文件和对应的行

空格的有和没有

定义变量时, =号的两边不可以留空格

1
gender=femal

条件测试语句 [ 符号的两边都要留空格
1
if [ $gender = femal ]; then

条件测试的内容,如果是字符串比较的话, 比较符号两边要留空格

1
if [ $gender = femal ]; then

如果if 和 then写在同一行, 那么,注意, then的前面要跟上 ; 号.如果 then 换行写, 那么也没问题.

1
2
if [ $gender = femal ]
then

命令和其后的参数或对象之间一定要有空格

1
if [ -x"~/Workspace/shell/a.sh" ];then

取字符串的某一段

1
2
3
4
5
6
7
#/bin/bash -e

ip="192.168.0.123"
net=$(cut -d'.' -f3<<<"192.162.0.123") # 3个<
sub=$(echo $ip | cut -c1-7) # -c 一般用于文件,比如 cut -c1-4 test.txt
echo $net
echo $sub

结果是:

1
2
0
192.168

cut命令一般用于处理表内容,例如只取某一列
-c:仅显示行中指定范围的字符;
-d:指定字段的分隔符,默认的字段分隔符为”TAB”;
-f:显示指定字段的内容;

使用awk的内建函数:

1
2
3
hostname -I | awk '{split($0,a,".");print a[1],a[2],a[3],a[4]}'   # 192 168 0 123

hostname -I | awk '{print substr($0,0,4)}' # 192.

所以如果想获得ip的网段,可以使用net=$(hostname -I | awk '{split($0,a,".");print a[3]}')

列出当前目录下,最大的10个文件

ls -Slh | head

连接字符串

如果想要在变量后面添加字符,可以用以下方法:

1
2
3
4
5
$value1=home

$value2=${value1}"="  # 用单引号也行

echo $value2

把要添加的字符串变量添加{},并且需要把$放到外面。这样输出的结果是home=,连接成功。

echo

echo换行

echo要支持同C语言一样的\转义功能,只需要加上参数-e

echo -e “\n” 就是换行
echo -e $(cat test.txt)
其中test.txt的内容:

1
aaa \nbbb

结果就是:
1
2
aaa
bbb

不要加双引号,那样会保留下来

echo文本到文件

echo换行的文本

1
2
3
echo -e "Hello\nworld"
echo -e 'Hello\nworld'
echo Hello$'\n'world

echo $(cat 1.txt) > 2.txt可以把文件1的内容复制到文件2。但如果文件1每行结尾没有加\n,文件2的内容不会换行。另外这样会覆盖文件2原有的内容。如果不想覆盖,而是追加到文件2,只要把>改为>>即可


不要显式调用构造函数和析构函数

常用的代码如下:

1
2
Base b;
cout<<"hello"<<endl;

结果:
1
2
3
基类构造 0x62fe84
hello
基类析构0x62fe84

但是这样的代码就不同了:

1
2
Base();		// 匿名的临时对象
cout<<"hello"<<endl;

运行结果:
1
2
3
基类构造 0x62fe84
基类析构0x62fe84
hello

可见临时创建的类对象立刻销毁了,这与平时创建在stack上的对象再出了局部范围再销毁是不同的。

看这样的代码,是关于显式调用构造函数导致的成员变量未初始化问题:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class CTest  
{
public:
CTest()
{
m_a = 1;
}
CTest(int b)
{
m_b = b;
CTest();
}
~CTest() {}
void showA()
{
std::cout<<"a:"<<m_a;
}
private:
int m_a;
int m_b;
};

void main()
{
CTest myTest(2);
t.showA();
}

结果是a:6487936,也就是m_a未初始化。这里我们创建的对象是myTest,希望对其成员m_a初始化,但在构造函数里显式调用另一个构造函数,实际上是创建了一个临时对象,这个对象对m_a初始化了,这跟myTest是没有关系的,而且它很快又销毁了,所以没有达到目的。

这样的代码也是有问题的:

1
2
3
Base b;
b.~Base();
cout<<"hello"<<endl;

结果是二次析构了:

1
2
3
4
基类构造 0x62fe84
基类析构 0x62fe84
hello
基类析构 0x62fe84

所以不要显式调用构造函数和析构函数,这是危险的。


fprintf,snprintf和sprintf函数

fprintf

原型:extern int fprintf (FILE *f,const char *s, ...);
可以将字符串输出到某文件中,但更常用的用法是:

1
2
fprintf(stdout,"Hello\n");	 //加换行
fprintf(stderr,"World!");

输出Hello换行World。stdout是行缓冲的,输出会放在一个buffer里面,只有到换行的时候,才会输出到屏幕。而stderr是无缓冲的,会直接输出。

snprintf

int snprintf(char *restrict buf, size_t n, const char * restrict format, ...);
函数说明:最多从源串中拷贝n-1个字符到目标串中,然后再在后面加一个0。所以如果目标串的大小为n的话,将不会溢出。
函数返回值:若成功则返回欲写入的字符串长度,若出错则返回负值。

1
2
3
4
5
6
7
8
9
char s1[6] = "12345";
char s2[6] = "67890";
int res;
res = snprintf(s1,sizeof(s1),"abcdefg"); //写入长度大于原来长度,写入abcde和\0,要求6
printf("s1:%s, res:%d\n",s1,res); //欲写入长度7,这个值是strlen,不包含\0
res = snprintf(s1,sizeof(s1),"abc"); //写入长度少于原来长度,则相当于替换
printf("s1:%s, res:%d\n",s1,res);
res = snprintf(s2,4,"%s","abcdefg"); //指定4,包含了\0
printf("s2:%s, res:%d\n",s2,res);

结果:
1
2
3
s1:abcde, res:7
s1:abc, res:3
s2:abc, res:7

sprintf

int sprintf(char *buffer, const char *format, [ argument] … );
函数功能:把格式化的数据写入某个字符串缓冲区。

函数不安全,写入目标时不会考虑字符数组的大小,要存储的字符超过数组长度时,会导致数组越界,编译不报错但运行报错,所以都会推荐使用snprintf.

1
2
3
4
5
6
char s1[6] = "12345";
int res;
res = sprintf(s1, "%s","abcdefg"); //超出原字符数组长度,不安全
printf("s1:%s, res:%d\n",s1,res);
res = sprintf(s1, "%s","abc");
printf("s1:%s, res:%d\n",s1,res);

结果:
1
2
s1:abcdef, res:7
s1:abc, res:3


char数组和指针问题

这个问题是C++基础问题中相当折腾人的一个,死记硬背解决不了根本问题,记住还是要忘,需要仔细研究其本质。

这两种方式就是数组和指针的方式:

1
2
char a[6] = "abcde";
char *b = "abcde";

第一行声明了并初始化了一个char数组,第二行是声明char指针b,指向了常量字符串。其中a是数组的首地址,a和b的地址一定不同。

千万不能说数组名是指针,可以用sizeof来否定:

1
2
char a[]="abcde";
cout<<sizeof(a)<<endl;

如果a是个指针,那么结果是4,但结果是6.

数组不能被直接复制,所以当数组名作为函数参数的时候,要么就是数组的引用,要么就是指向第一个元素的指针,他们的值是相等的。当你对一个数组做&的时候,他提取的是指向数组的指针,然后仍然可以隐式转换成指向第一个元素的指针,而且它们的值是相等的。

这样的代码是错的:

1
2
char a[6] = "abcde";
a[6] = "asdfge";

只有声明里才能用a[6],这就好比int a[6]={1,2,3,4,5,6};,但不能再用a[6]={5,6,7,8,9,0};。应该用a[0]='A';

这样的代码是正确的:

1
2
3
char a[]="abcde";
char *b;
b = a;

b是指针变量,指向了数组的首地址。

这样是错的:

1
2
3
char *a="abcde";  或者  char a[]="abcde";
char b[6];
b = a;

实际上是上一种情况的相反,报错error: incompatible types in assignment of 'char*' to 'char [6]'因为不存在一个隐式转换使得 char 被转换成 char[]。这个问题比较关键,我们可以把数组名b理解成一个常量指针,它不能指向其他地址,但指向的字符串可以改变。但是注意只是这么理解而已,数组名并不真的是常量指针。同样的,b++;也是错的。
从另一个角度来看,*数组名做函数参数时会退化为指针
,这里没有退化为指针的条件,所以b不能当指针变量用。

这样也是错的:

1
2
char a[6];
a = "abcde";

a是数组的首地址,怎么把字符串常量赋给它?

再看这种情况:

1
2
3
char *a, *b;
a = "abcde";
b = "abcde";

a和b的值不一定相同,也就是不一定是同一个地址,这取决于编译器的行为。

对于char指针和数组,以下操作都是可行的。

1
2
3
4
5
6
7
8
9
10
11
const char* p="abcd";	//在常量区,应当加const,否则编译器会报警
// char p[]="abcd"; // 在stack
cout<<p<<endl; // abcd
cout<<&(*p)<<endl; //abcd
cout<<*p<<endl; // a
cout<<&p<<endl; // 0x62fe9c

cout<<p+2<<endl; //cd
cout<<*(p+2)<<endl; //c
cout<<*p+2<<endl; //99
cout<<p[2]<<endl; //c

但下面操作仅适用于char数组,不能用于指针,指针指向的是常量:

1
//p[0]='A';

对于数组char p[]="abcd";,可以使用p[2],这是因为数组名在这里退化为指针,p转为指向数组首元素的char*类型。也就是说指针本身就可以用[],反而是数组名需要先转换为指针才能用[]。看下面的例子:
1
2
3
4
5
6
int b[5] = {1,2,3,4,5};
int *f=b;
cout<<f[2]<<endl; // 3
f[2]=0;
cout<<f[2]<<endl; // 0
cout<<b[2]<<endl; // 0

对于常量字符串,都可以用数组下标,这种做法比较少见:

1
cout<<"abcd"[2];     //c


new与delete

对类类型而言,new运算是先分配内存再执行构造函数,delete是先执行析构函数再释放内存

对array的用法

我们都知道new与delete经常这样用:

1
2
3
4
5
int* a = new int(10);
delete a;

int* b = new int[10];
delete []b;

如果第二种情况改用delete b;会不会有内存泄漏? 答案是仍然不会,分配简单类型内存时,内存大小已经确定,系统可以记忆并且进行管理,在析构时,系统并不会调用析构函数。它直接通过指针可以获取实际分配的内存空间,哪怕是一个数组内存空间。

但是对于类对象就不能这样用了,看下面的类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Base
{
public:
Base()
{
std::cout<<"基类构造 "<<this<<endl;
}
virtual ~Base()
{
std::cout<<"基类析构"<<this<<endl;
}
};
Base* pb = new Base[5];
delete pb;

运行结果如下,有5个构造,但只有1个析构函数,而且从this指针来看,是数组第一个元素的析构函数:
1
2
3
4
5
6
7
基类构造 0xe118d4
基类构造 0xe118ec
基类构造 0xe11904
基类构造 0xe1191c
基类构造 0xe11934

基类析构 0xe118d4

delete pb只用来释放pb指向的内存和一个析构。delete[] pb用来释放指针指向的内存,还逐一调用数组中每个对象的析构。 所以为了编程规范,不管对简单类型还是类类型,都要用delete []pb的形式。

与malloc/free的区别

  • new/delete用于C++中的动态内存分配; malloc/free仅用于C环境,用于类类型时,不会运行构造析构函数

  • new/delete不必指定分配内存大小,malloc/free必须指定

  • new返回的是指定对象的指针,而malloc返回的是void*malloc的返回值一般都需要进行类型转化。

  • new是一个操作符可以重载,malloc是一个库函数

比如:

1
2
Base* b = (Base*)malloc(12);
free(b);

12是随便指定的,结果不运行构造和析构函数,而且如果中间运行成员函数,程序会崩溃。 所以这种代码没有任何意义


函数在main之前或之后运行
  • C++中,全局对象的构造函数在main之前运行,析构函数在main之后运行。
  • 类静态变量的初始化在main之前,静态函数不行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Base
{
public:
Base()
{
std::cout<<"基类构造"<<endl;
}
~Base()
{
std::cout<<"基类析构"<<endl;
}
static int get()
{
std::cout<<"get()"<<endl;
return 55;
}
static int count;
}

// main.cpp
Base b;
// int Base::count = Base::get(); 错误,这里不能调静态函数
int main()
{
std::cout<<"main "<<endl;
return 0;
}

运行结果:

1
2
3
4
基类构造
get()
main
基类析构

gcc中使用attribute关键字,声明constructor和destructor函数:

1
2
3
4
5
6
7
__attribute__((constructor)) void before_main() { 
printf("before main\n");
}

__attribute__((destructor)) void after_main() {
printf("after main\n");
}

如何在程序退出时运行函数

很多时候我们需要在程序退出的时候做一些诸如释放资源的操作,但程序退出的方式有很多种,比如main()函数运行结束、在程序的某个地方用exit()结束程序、用户通过Ctrl+C或Ctrl+break操作来终止程序等等,因此需要有一种与程序退出方式无关的方法,在退出时执行某函数。方法就是用atexit()函数来注册程序正常终止时要被调用的函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cstdlib>

void atexit_handler_1()
{
std::cout << "at exit #1\n";
}

void atexit_handler_2()
{
std::cout << "at exit #2\n";
}

QApplication a(argc, argv);

const int result_1 = std::atexit(atexit_handler_1);
const int result_2 = std::atexit(atexit_handler_2);

if ((result_1 != 0) || (result_2 != 0)) {
std::cerr << "Registration failed\n";
return EXIT_FAILURE;
}
MainWindow w;
w.show();
return a.exec();

atexit执行成功,返回0,否则返回非0.

当程序正常终止(调用exit()或者由main函数返回)时,调用atexit()参数中指定的函数。


运算符重载(二)

以一个Point类为例,重载几个运算符,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Point
{
public:
Point(int x=0,int y=0)
{
arr[0] = x;
arr[1] = y;
}
void print()
{
cout<<"x: "<<arr[0]<<" y: "<<arr[1]<<endl;
}

int& operator [](int num)
{
assert(num==1 || num==0);
if(num==0)
return arr[0];
else if(num==1)
return arr[1];
}
Point& operator -()
{
return Point(-arr[0],-arr[1]);
}
Point& operator --()
{
return Point(arr[0]-1,arr[1]-1);
}
Point& operator ++()
{
return Point(arr[0]+1,arr[1]+1);
}
Point& operator +(Point& p)
{
return Point(arr[0]+p.arr[0], arr[1]+p.arr[1]);
}
Point& operator -(Point& p)
{
return Point(arr[0] - p.arr[0], arr[1] - p.arr[1]);
}
bool operator ==(const Point& p)
{
return ((arr[0]==p.arr[0]) && (arr[1]==p.arr[1]) )
}
private:
int arr[2];
};

有一个数组做成员变量,构造函数给数组赋值。
首先是一元运算符- -- ++,显然是无参数的。返回值应当是Point&,函数也容易理解。
二元运算符加法和减法及相等也简单,有一个参数而已。其实这三个运算符由于是双目的,最好按友元重载。

下标运算符重载的声明必须是返回类型& operator [](参数),只能作为类成员函数,不能做友元。

调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
Point p(1,4);
//改变 p
p[0] = 7;
p[1] = 9;
Point p1 = -p;
Point p2(4,12);
Point p3 = p - p2;
if(p2==p3)
cout<<"equal"<<endl;
else
cout<<"not equal"<<endl;
Point p4 = ++p3;
Point p5 = --p3;

参考:C++ 运算符重载