我编写了以下 C++ 代码,试图理解 C++ 中的复制省略。
#include <iostream>
using namespace std;
class B
{
public:
B(int x ) //default constructor
{
cout << "Constructor called" << endl;
}
B(const B &b) //copy constructor
{
cout << "Copy constructor called" << endl;
}
};
int main()
{
B ob =5;
ob=6;
ob=7;
return 0;
}
这会产生以下输出:
Constructor called
Constructor called
Constructor called
我不明白为什么构造函数在每次赋值给对象 ob 时被调用三次。
最佳答案
B ob =5;
这使用给定的构造函数。
ob=6;
这使用给定的构造函数,因为没有 B& operator=(int)
函数并且 6
必须转换为 B
类型。一种方法是临时构造一个 B
并在作业中使用它。
ob=7;
同上答案。
I fail to understand why is the constructor being called thrice with each assignment
如上所述,您没有 B& operator=(int)
函数,但编译器很乐意提供复制赋值运算符(即 B& operator=(const B&) ;
) 给你automatically .正在调用编译器生成的赋值运算符,它采用 B
类型,所有 int
类型都可以转换为 B
类型(通过构造函数你提供了)。
注意:您可以使用 explicit
(即 explicit B(int x);
)禁用隐式转换,我建议使用 explicit
除非需要隐式转换。
例子
#include <iostream>
class B
{
public:
B(int x) { std::cout << "B ctor\n"; }
B(const B& b) { std::cout << B copy ctor\n"; }
};
B createB()
{
B b = 5;
return b;
}
int main()
{
B b = createB();
return 0;
}
示例输出
注意:使用 Visual Studio 2013(发布版)编译
B ctor
这表明复制构造函数被省略(即 createB
函数中的 B
实例被触发但没有其他构造函数)。
关于c++ - 多次调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31300904/