Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

c++ - Copy constructor not called?

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because of Return Value Optimization the 3rd test case's copy constructor call is optimized away by the compiler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...