以前一直没想过这个问题,如果fork一个进城以后,那对一个对象是调用拷贝构造函数或者构造函数?
做了个实验,发现都没调用,后来查资料,进程的地址都是虚拟地址,fork以后相当于在原先进程地址做了一个一摸一样的镜像地址。所以将出现一次构造函数,2次析构函数的情况
class mystring
{
public:
mystring(char *s = NULL)
{
cout<<"mystring"<
if (s == NULL)
{
str = new char[1];
str[0] = 0;
}
int len = strlen(s)+1;
str = new char[len];
strcpy(str,s);
}
~mystring()
{
cout<<"~mystring"<
if (str != NULL)
delete []str;
}
mystring(const mystring& s1)
{
str = s1.str;
cout<<"copy construct"<
}
private:
char *str;
};
int main()
{
mystring s("abc");
pid_t pid;
if ((pid = fork()) < 0)
{
cerr<<"fork error"<
}
else if (pid == 0)
{
//sleep(1);
cout<<"child running"<
}
else
{
if (waitpid(pid,NULL,0) != pid)
cerr<<"waited error"<
}
return 0;
}
运行结果是
mystring
child running
~mystring
~mystring
没有调用拷贝构造和构造函数
在多线程中,当然不存在这个问题,我实验时发现子线程中的对象在子线程退出后调用析构函数
void *thr_fn(void *arg)
{
mystring s1("abcd");
cout<<"thread child running"<
pthread_exit((void *)1);
}
int main()
{
mystring s("abc");
int err;
void *tret;
pthread_t tid1,tid2;
err = pthread_create(&tid1,NULL,thr_fn,NULL);
if (err != 0)
cerr<<"create pthread"<
err = pthread_join(tid1,&tret);
cout<<"return main thread"<
return 0;
}
实验结果
mystring
mystring
thread child running
~mystring abcd
return main thread
~mystring abc
阅读(1343) | 评论(0) | 转发(0) |