Uh oh!
There was an error while loading. Please reload this page.
fix: 实用小技巧中的一些错误 - #90
Conversation
sweet2honey
commented
Jun 4, 2025
|
感谢回答。
intfunc(int a){
int res = 0;
/* some code to change value res;*/return res;
}这正是单一出口原则的体现。
2.由于第一次提pr对markdown规范不是很熟悉,后续pr会注意的。 |
sweet2honey
commented
Jun 4, 2025
我见过比较好的 |
frederick-vs-ja
commented
Jun 6, 2025
很多人,包括我,视这种单一出口原则为反模式(anti-pattern)。不少代码库更青睐提前退出。 |
archibate
commented
Aug 15, 2025
c语言没有raii才需要单一出口,cpp不需要。 intdo_something() {
intret=0;
FILE*fp=fopen("path.txt");
if (!fp) {
ret=-1;
goto out;
}
if (...) {
ret=-2;
goto out_fp;
}
out_fp:
fclose(fp);
out:
returnret;
}本质上是在用goto模拟析构函数的调用顺序,看似好像只有单一返回,实际上依然是提前返回的,每一次的goto语句不正是提前返回吗。 intdo_something() {
intret=0;
ifstreamfp("path.txt");
if (!fp) {
return-1;
}
if (...) {
return-2; // 自动调用 fp 的析构
}
return0; // 自动调用 fp 的析构
} |
1.提前结束语句的demo多出口违背了单一出口原则
2.lambda使用&捕获,并未直接使用外部变量,在()添加形参才对