小编Kam*_*Pop的帖子

为对象分配值时为什么调用构造函数和析构函数

我有以下代码:

#include <iostream>

using namespace std;

class A{
    int x;
public:
    A(int x =1) : x(x) {cout << "A() ";}
    A(const A& a) {x =a.x; cout << "A(const A&) ";}
    A& operator=(const A& a){cout << "op= "; x=a.x; return *this;}
    ~A(){cout << "~A()";}
    int getX() {return x;}
    void setX(int x){this->x = x;}
};


A g(A a){
    //a = 2;
    cout << "g() ";
    a.setX(3);
    return a;
}

int main()
{
    A a;
    a = 2;

}
Run Code Online (Sandbox Code Playgroud)

我期望有以下输出:A() op= ~A() …

c++ constructor destructor assignment-operator

2
推荐指数
1
解决办法
61
查看次数

使用 fork 时 while(wait(NULL)){} 和 while(wait(NULL) &gt; 0){} 有什么区别

我有以下代码:

#include<stdio.h>
#include<stdlib.h> 
#include<sys/wait.h> 
#include<unistd.h> 

int main() {
for(int i = 0; i <3; i++){
    fork();
}
while(wait(NULL)){}
printf("Text\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试执行它时,我SIGKILL从 fork 调用中收到一条错误,而不是收到 8 条短信。但是,如果我改变

while(wait(NULL)){}
Run Code Online (Sandbox Code Playgroud)

while(wait(NULL) == 0){} 
Run Code Online (Sandbox Code Playgroud)

或者

while(wait(NULL) > 0){}
Run Code Online (Sandbox Code Playgroud)

我按预期收到了 8 张“文本”打印件。

为什么程序在第一种情况下不起作用?wait(NULL)循环或循环不是wait(0)应该等到所有子进程执行完毕吗?

谢谢您的帮助!

c posix fork wait

2
推荐指数
1
解决办法
980
查看次数

标签 统计

assignment-operator ×1

c ×1

c++ ×1

constructor ×1

destructor ×1

fork ×1

posix ×1

wait ×1