【发布时间】:2018-01-20 20:12:48
【问题描述】:
这是我不知何故错过的一件事,但我很惊讶。考虑以下代码示例:
#include <iostream>
class A
{
int a;
public:
A(int a) : a(a) { std::cout << "Normal constructor called." << std::endl; }
A(const A& orig) : a(orig.a) { std::cout << "Copy constructor called." << std::endl; }
};
void testFunction1(const A arg) { std::cout << "testFunction1()" << std::endl; }
void testFunction2(const A& arg) { std::cout << "testFunction2()" << std::endl; }
int main()
{
testFunction1(A(2));
testFunction2(A(2));
return 0;
}
我期望得到以下结果:
/* Normal constructor called. */
/* Copy constructor called. */
/* testFunction1() */
/* Normal constructor called. */
/* testFunction2() */
但我错了。确切的结果如下:
/* Normal constructor called. */
/* testFunction1() */
/* Normal constructor called. */
/* testFunction2() */
当我将A(2) 按值传递给testFunction1() 时,为什么没有调用复制构造函数?这是否意味着在 C++98 中通过值或引用传递右值没有区别?是优化吗? A(2) 和 arg 完全一样 testFunction1() 中的对象吗?
【问题讨论】:
-
可能是copy elision。
-
@Someprogrammerdude - 谢谢,我会检查的。以前从未听说过。
-
如果您从未听说过,那么您可能会阅读一些不错的 C++ 书籍...强烈推荐 Meyers 和 Sutter 书籍。跨度>
标签: c++ oop copy-constructor pass-by-value c++98