gpt4 book ai didi

c++ - 了解临时对象上下文中的函数调用

转载 作者:太空狗 更新时间:2023-10-29 23:25:26 27 4
gpt4 key购买 nike

看看这个简单的代码:

class A
{};

A f(A a)
{
return a;
}

int main(void)
{
A a;
A b = f(a);
return 0;
}

它创建一个局部变量a,调用一个函数f()并将它的返回值赋给另一个变量b。但我想知道函数调用期间发生了什么。

有人可以向我描述一下,在此过程中创建了哪些对象(临时对象或其他对象),调用了哪些构造函数、析构函数和赋值/移动运算符以及何时调用?

最佳答案

如有疑问,请拿出 Noisy类:

struct Noisy {
Noisy() { std::cout << "Default construct" << std::endl; }
Noisy(const Noisy&) { std::cout << "Copy construct" << std::endl; }
Noisy(Noisy&&) { std::cout << "Move construct" << std::endl; }
Noisy& operator=(const Noisy&) { std::cout << "Copy assignment" << std::endl; return *this; }
Noisy& operator=(Noisy&&) { std::cout << "Move assignment" << std::endl; return *this; }
~Noisy() { std::cout << "Destructor" << std::endl; }
};

Noisy f(Noisy a) {
return a;
}

int main(void) {
Noisy a;
Noisy b = f(a);
}

使用选项 g++ -fno-elide-constructors -std=c++11 t.cc 使用 gcc-4.9.1 编译给出输出:

Default construct // 1. 'a' is default constructed.
Copy construct // 2. Local argument 'a' in function 'f' is copied.
Move construct // 3. Return value is move constructed (*see note below).
Move construct // 4. 'b' is move constructed from return value.
Destructor // 5. Local argument 'a' is destroyed.
Destructor // 6. Return value is destroyed.
Destructor // 7. 'b' is destroyed.
Destructor // 8. 'a' is destroyed.

注意:即使本地参数a是左值,编译器知道它即将超出范围并将其视为右值。

编译没有选项-fno-elide-constructors将启用编译器复制省略优化并产生输出:

Default construct // 1. 'a' is default constructed.
Copy construct // 2. Local argument 'a' in function 'f' is copied.
Move construct // 3. 'b' is move constructed from argument 'a' (elision).
Destructor // 4. Local argument 'a' is destroyed.
Destructor // 5. 'b' is destroyed.
Destructor // 6. 'a' is destroyed.

使用 -std=c++03 编译即 C++03 将导致所有移动都被拷贝替换。

有关复制省略的更多信息,请参阅此处:What are copy elision and return value optimization?

关于c++ - 了解临时对象上下文中的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26493902/

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