c++ - 函数参数不调用构造函数?

标签 c++ constructor destructor pass-by-value

所以,这可能是一个令人尴尬的问题。我正在强化我的 C++ 基础知识,但遇到了这个奇怪的案例。

有趣的是,在进入函数时,不会为对象 lb 调用构造函数,但在离开函数时,我推测会为 lb 调用析构函数。

这怎么可能?当它们进入函数时,应该调用构造函数和析构函数。或者,如果只调用析构函数,那么我预计会导致段错误?

#include <iostream>    
using namespace std;

class B {
public:
  B() {
    cout<<"Construct B"<<endl;
  }
  virtual ~B() {
     cout<<"Destruct B"<<endl;
  }
};

bool FuncByVal(B lb)
{
   return true;
}

int main(int argc, char* argv[])
{
   B b;
   FuncByVal(b);
   return 0;
}

输出是: 构造B 破坏B 破坏B

我在 Windows 8.1 下的 Visual Studio 2012 和 Windows 8.1 下使用 MinGW 的 Eclipse 上进行了测试。

另外,我也在 Linux (eclipse+gcc) 下进行了测试,以确保万无一失。

附注对于按引用复制,输出如我所料,即,同一代码仅调用了一个构造函数调用和一个析构函数。

最佳答案

被调用的是对象的复制构造函数,而不是它的默认构造函数。由于您没有明确定义复制构造函数 compiler defined it implicitly (当然没有输出)。

class B {
public:
  B() {
    cout<<"Construct B"<<endl;
  }

  /// Add this
  B(const B&) {
    cout<<"Copy B"<<endl;
  }

  virtual ~B() {
     cout<<"Destruct B"<<endl;
  }
};

关于c++ - 函数参数不调用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30155262/

相关文章:

Java构造函数: creating an object,短参数被解释为int

c++ - 析构函数调用删除函数时程序崩溃

c - 像 C 中的析构函数这样的机制?

android - 错误 : undefined reference to '_jstring* QAndroidJniObject::callStaticMethod<_jstring*>(char const*, char const*)'

c++ - 对象状态快照的 DRY 方法

java - 如何处理防御性编程的各种情况?

C++ 控制全局对象的析构函数顺序

c++ - struct constructor会占用struct空间内的空间吗?

c++ - 为什么我的 map 打印全为零?

php - 交响乐 4 : How to pass the $_SERVER array as constructor argument