Copy constructor not called?(没有调用复制构造函数?)
问题描述
据我所知,您在以下情况下调用复制构造函数:
1 实例化一个对象并使用另一个对象的值对其进行初始化时
2 按值传递对象时.
3 当一个对象按值从函数返回时.
我决定对此进行测试,并制作了这个小程序来测试它(每次调用构造函数时都会显示消息.它似乎适用于前两种情况,但不适用于第三种情况.我想找出我的错误. 欢迎提出想法.
As far as I know you call the copy constructor in the following cases:
1 When instantiating one object and initializing it with values from another object
2 When passing an object by value.
3 When an object is returned from a function by value.
I decided to put this to the test and I made this small program testing this (with messages each time a constructor is called. It seems to work for the first two cases, but not for the third one. I want to find out my mistake. Ideas are welcomed.
#include <iostream>
using namespace std;
class Circle{
private:
double* data;
public:
Circle();
Circle(double* set);
Circle(const Circle& tt1);
~Circle();
Circle& operator=(const Circle& tt1);
};
Circle :: Circle()
{
cout << "Default constructor called" << endl;
data = NULL;
}
Circle :: Circle(double* set)
{
cout << "Set up constructor called" << endl;
data = new double[3];
copy(set, set+3, data);
}
Circle :: Circle(const Circle& tt1)
{
cout << "Copy constructor called" << endl;
data = new double[3];
copy(tt1.data, tt1.data+3, this->data);
}
Circle :: ~Circle()
{
cout << "Destructor called!" << endl;
delete[] data;
}
Circle& Circle :: operator=(const Circle& tt1)
{
cout << "Overloaded = called" << endl;
if(this != &tt1)
{
delete[] this->data;
this->data = new double[3];
copy(tt1.data, tt1.data+3, this->data);
}
return *this;
}
void test2(Circle a)
{
}
Circle test3()
{
double arr [] = { 3, 5, 8, 2};
Circle asd(arr);
cout<< "end of test 3 function" << endl;
return asd;
}
int main()
{
cout <<"-------------Test for initialization" << endl;
double arr [] = { 16, 2, 7};
Circle z(arr);
Circle y = z;
cout << "-------------Test for pass by value" << endl;
test2(z);
cout <<"------------- Test for return value-------"<<endl;
Circle work = test3();
cout<< "-----------Relese allocated data" << endl;
return 0;
}
推荐答案
因为返回值优化 第三个测试用例的拷贝构造函数调用被编译器优化掉了.
Because of Return Value Optimization the 3rd test case's copy constructor call is optimized away by the compiler.
这篇关于没有调用复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:没有调用复制构造函数?
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01