c++ - 多次调用构造函数

标签 c++

我编写了以下 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/

相关文章:

c++ - 预处理器保持宏

c++ - 从 Excel 文件读取

c++ - 为什么 omnet++ 4.6 模拟在运行时停止?

c++ - MAT channel 的平均值

c++ - 为什么必须在 C++ 类定义中声明方法?

c++ - 函数调用中创建的对象和传入的对象有什么区别

c++ - 使用前向引用

c++ - 在 C++ 中拆分一个字符串(使用 strtok?),用逗号分隔符分隔并且不使用外部库?

c++ - GCC 左移严重错误

c++ - 如何在 clang 中打印完全合格的 Expr?