can you please help me understand this cctor issue?
I wrote simple code in order to call the copy ctor:
#include <iostream>
using namespace std;
class point
{
public:
// Ctor's
point(int a_);
// Cctor
point(const point&); //= delete;
private:
int a;
};
point::point(const point& p_)
{
cout << "This is a cctor (copy ctor)" << endl;
}
point::point(int a_)
{
a = a_;
cout << "This is point(a) ctor" << endl;
}
int main()
{
point p1(1);
point p2 = 4;
return 0;
}
I found out that in the case:
point p2 = 4;
The output was:
This is point(a) ctor
This is point(a) ctor
but if changing the initialization to:
point p2 = p1;
The output was:
This is point(a) ctor
This is a cctor (copy ctor)
So far so good, I assumed the compiler is using optimization and not calling cctor for "point p2 = 4;" but only the ctor.
But than, when deleting the cctor explicitly: (and removing the definition, of course)
point(const point&) = delete;
In both cases: ("point p2 = p1;" and "point p2 = 4;") I got the same result:
try.cpp:32:16: error: use of deleted function ‘point::point(const point&)’
point p2 = p1;
^
try.cpp:12:5: error: declared here
point(const point&) = delete;
^
Any idea what is happening here?
Is "p2 = 4;" calls cctor or not, and how come the behaviour changes?
NOTE: I compiled using g++ with -std=c++11 flag on a CentOS7.
Aucun commentaire:
Enregistrer un commentaire