将对象传递给函数并不是导致构造函数调用
passing an object to a function is not resulting into a constructor call
当我在以下代码中调用f1时,不应该打电话给构造函数吗?我看到"这个"指针在对象b(param到f1(中有所不同,这意味着创建了一个新对象,但是我看不到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 . . .
,因为当您按值传递对象时,对象被复制,因此复制构建器将被调用。
正如已经指出的那样,您需要在A类中添加复制构造函数。这是应该的外观:
A(const A&)
{
printf("Inside copy constructorn");
}
相关文章:
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 使用 std::variant<...时调用 BaseState 函数而不是派生函数>
- 是同一作用域的函数部分中的函数调用
- 为什么调用复制构造函数而不是移动构造函数?
- 使用基类指针调用基类的值构造函数的语法是什么?
- C++:使用方法调用析构函数的顺序是什么?
- 即使没有调用这个递归函数,它是如何工作的?
- 使用动态链接加载程序 <dlfcn.h> 而不是直接函数调用的目的是什么?
- Tbb 库:错误:编写自定义类函数而不是 lambda 表达式时,对函数的调用不匹配
- 为什么在传递给函数而不是构造函数时调用析构函数?
- 通过指针调用模板类成员函数 [为什么这是有效的 c++]?
- 内联asm编译器屏障(内存阻塞器)是算作外部函数,还是算作静态函数调用
- 调用值构造函数而不是复制构造函数
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- 将对象传递给函数并不是导致构造函数调用
- 在cpp中创建嵌套对象.下面的伪代码中的函数调用序列是什么
- 从catch块调用异常类中的函数并不是打印从try块传递的值
- R6025 纯虚函数调用:什么是以及如何解决
- Libpng函数调用都是未解析的外部符号