您能帮我理解cctor问题吗?
我写了简单的代码来调用副本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;
}
我发现这种情况:
point p2 = 4;
输出为:
This is point(a) ctor
This is point(a) ctor
但是如果将初始化更改为:
point p2 = p1;
输出为:
This is point(a) ctor
This is a cctor (copy ctor)
到目前为止,一切都很好, 我假设编译器正在使用优化,而不是为“ point p2 = 4;”调用cctor。但只有ctor。
但是,当显式删除cctor时:(当然也要删除定义)
point(const point&) = delete;
在两种情况下:(“ point p2 = p1;”和“ point p2 = 4;”)我得到了相同的结果:
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;
^
有什么想法吗?
是“ p2 = 4;”是否呼叫cctor,行为如何变化?
注意:我在CentOS7上使用带有-std = c ++ 11标志的g ++进行编译。