c++ - 没有段错误为什么?返回的函数值用作参数

标签 c++ function segmentation-fault

下面的代码会导致段错误吗?

struct Dim {
  int x, y, z;
};

Dim set_dim(int a) {
 Dim l;
 l.x=a;
 l.y=a;
 l.z=a;
 return l;
}

int sum(const Dim &m) {
  int s=m.x+m.y;
  return s;
}

main() {
  cout<<sum(set_dim(5))<<endl;
}

我认为可以,因为在 set_dim 中引用了局部变量“l”,换句话说,引用了现在超出范围的变量。但它的作用丝毫不减

最佳答案

这是明确定义的。 set_dim按值返回,所以它返回的对象是局部变量l的临时拷贝.然后将此临时绑定(bind)到 const sum 的引用参数.这会影响临时对象的生命周期:

A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.

因此临时对象的生命周期是完整表达式 cout<<sum(set_dim(5))<<endl; . sum 时它仍然存在正在执行。

关于c++ - 没有段错误为什么?返回的函数值用作参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16132252/

相关文章:

python - 确定从哪个文件在python中定义了一个函数

javascript - typeof 2D 数组将变为 String。为什么?

c - 打印出指针指向的值(C编程)

c++ - 我收到此代码的段错误?

c++ - 为什么 std::lerp 不适用于任何已实现所需操作的类型?

c++ - 在链接行中包含额外的库

c++ - C处理局部变量

c++ - 为什么 C++ 中的可变大小数组 (VLA) 需要具有自动 (auto) 存储类?

解决 R 函数中的 nrow/length(list) 错误

c - getline()/strsep() 组合导致段错误