gpt4 book ai didi

c++ - 在函数的参数列表中初始化的变量的范围

转载 作者:IT老高 更新时间:2023-10-28 12:50:39 27 4
gpt4 key购买 nike

以下代码构建、编译和运行(C++、mingw)似乎没有任何问题。但是,我是否可以保证在函数的参数列表中使用初始化列表构造的对象存在于该函数的范围内,即使该函数通过引用获取参数?

如果不是,那么在函数的参数列表(通过引用获取参数)中使用其初始化器列表创建对象时是否会很危险,因为它会立即被破坏:在这种情况下,函数不会没有拷贝,而是对内存的引用,它可能会或可能不会被另一个进程重新分配?

struct S
{
S() : a(0), b(0) {}
S(int a, int b) : a(a), b(b) {}
int a;
int b;
};

void foo(const S& s)
{
std::cout << "s.a = " << s.a << std::endl;
std::cout << "s.b = " << s.b << std::endl;
}

int main()
{
foo({4,5}); // <-- What is the scope of the struct initialized here?

return 0;
}

最佳答案

根据cppreference [lifetime] :

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.

这意味着临时对象将在函数返回后被销毁,因此非常安全。

关于c++ - 在函数的参数列表中初始化的变量的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48786451/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com