c++ - 将对象传递给函数不会导致构造函数调用

标签 c++ function for-loop constructor

当我在下面的代码中调用 f1 时,是否应该调用构造函数? 我在对象 b(f1 的参数)中看到“this”指针不同,这意味着创建了一个新对象,但我没有在 b 的构造函数中看到打印。 但是有对析构函数的调用,谁能解释一下?

class A
{
    int k ;
public:
    A(int i)
    {
        k=i;
        printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this);
    }
    ~A()
    {
        printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this);
    }
    void A_fn()
    {
        printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this);
    }
};
void f1(A b)
{
    b.A_fn();
}
int _tmain(int argc, _TCHAR* argv[])
{
    A a(10);
    f1(a);
    return 0;
}

vc++ 2012 中显示的输出:

10 inside [A::A]ptr[00B3FBD0]

10 inside [A::A_fn]ptr[00B3FAEC]

10 inside [A::~A]ptr[00B3FAEC]

10 inside [A::~A]ptr[00B3FBD0]

Press any key to continue . . .

最佳答案

因为当您按值传递对象时,该对象被复制,因此将调用复制构造函数。

关于c++ - 将对象传递给函数不会导致构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44321535/

相关文章:

c++ - 错误 : invalid conversion from ‘int’ to ‘const char*’

JavaScript 在 'each' 循环内外声明函数

javascript - 在另一个回调中运行 jQuery 函数时出现问题

r - 将 for 循环的输出保存在单独的数据帧中

java - 尝试返回数组之和,方法调用错误

c++ - 如何在 DLL 中隐藏导出函数

c++ - 在异常 C++ 中抛出语法

c++ - 在区分源代码、目标代码、汇编代码和机器代码时,我感到困惑

c++ - 合法功能参数

python - CSV 循环遍历行