临时对象
#include <iostream>
#include <cstring>
#include <cstring>
using namespace std;
class Bar {
public:
Bar(const char* _name) {
cout << "ctor" << endl;
strcpy(name, _name);
}
Bar(const Bar& other) {
cout << "cp ctor" << endl;
strcpy(name, other.name);
}
virtual ~Bar() {
cout << "dtor" << endl;
}
public:
Bar(const char* _name) {
cout << "ctor" << endl;
strcpy(name, _name);
}
Bar(const Bar& other) {
cout << "cp ctor" << endl;
strcpy(name, other.name);
}
virtual ~Bar() {
cout << "dtor" << endl;
}
const char* getName() const{
return name;
}
return name;
}
void setName(const char* _name) {
strcpy(name, _name);
}
char name[256];
};
strcpy(name, _name);
}
char name[256];
};
Bar foo() {
return Bar("bar");
}
return Bar("bar");
}
int main() {
Bar bar(foo());
cout << foo().getName() << endl;
return 0;
}
Bar bar(foo());
cout << foo().getName() << endl;
return 0;
}
在VC和GCC中都没有调用过 copy constructor
输出
ctor
ctor
bar
dtor
dtor
ctor
bar
dtor
dtor
C++临时对象与拷贝构造函数调用分析
博客展示了一段C++代码,定义了Bar类,包含构造函数、拷贝构造函数和析构函数等。函数foo返回Bar类临时对象,在main函数中使用该临时对象。代码在VC和GCC中运行,未调用拷贝构造函数,并给出了具体输出结果。
1万+

被折叠的 条评论
为什么被折叠?



