gpt4 book ai didi

c++ - 从函数和复制构造函数返回的对象

转载 作者:搜寻专家 更新时间:2023-10-31 00:02:41 25 4
gpt4 key购买 nike

有这样的代码:

#include <iostream>

class A {
public:
int a;
A() : a(0) {
std::cout << "Default constructor" << " " << this << std::endl;
}
A(int a_) : a(a_) {
std::cout << "Constructor with param " << a_ << " " << this << std::endl;
}
A(const A& b) {
a = b.a;
std::cout << "Copy constructor " << b.a << " to " << a << " " << &b << " -> " << this << std::endl;
}
A& operator=(const A& b) {
a=b.a;
std::cout << "Assignment operator " << b.a << " to " << a << " " << &b << " -> " << this << std::endl;
}
~A() {
std::cout << "Destructor for " << a << " " << this << std::endl;
}
void show(){
std::cout << "This is: " << this << std::endl;
}
};


A fun(){
A temp(3);
temp.show();
return temp;
}


int main() {
{
A ob = fun();
ob.show();
}
return 0;
}

结果:

Constructor with param 3 0xbfee79dc
This is: 0xbfee79dc
This is: 0xbfee79dc
Destructor for 3 0xbfee79dc

对象 ob 由函数 fun() 初始化。为什么不在那里调用复制构造函数?我认为当函数按值返回时,将调用复制构造函数或赋值运算符。似乎在函数 fun() 中构造的对象在函数执行后没有被销毁。在这种情况下,如何强制调用复制构造函数?

这是由 g++ 编译的。

最佳答案

Why copy constructor is not called there?

RVO

How can be copy constructor forced to invoke in this case?

传递一个选项给编译器。对于 gcc,它是 --no-elide-constructors 选项来禁用 RVO

关于c++ - 从函数和复制构造函数返回的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7570152/

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