大家好,我有这个代码 Animal.h:
/*
* Animal.h
*
* Created on: May 27, 2015
* Author: saif
*/
#ifndef ANIMAL_H_
#define ANIMAL_H_
#include <iostream>
using namespace std;
class Animal {
int age;
public:
Animal();
Animal(const Animal & rhs);
Animal addTo();
virtual ~Animal();
};
#endif /* ANIMAL_H_ */
动物.cpp:
/*
* Animal.cpp
*
* Created on: May 27, 2015
* Author: saif
*/
#include "Animal.h"
Animal::Animal()
:age(0)
{
}
Animal::Animal(const Animal & rhs)
:age(rhs.age)
{
cout << "copy constructor activated" << endl;
}
Animal Animal::addTo()
{
Animal ret;
ret.age = 5;
return ret;
}
Animal::~Animal() {
cout << "NO not done, destructing.."<< endl;
}
main.cpp
#include <iostream>
using namespace std;
#include "Animal.h"
int main() {
Animal a;
Animal b = a.addTo();
cout << "done" << endl;
return 0;
}
输出:
done
NO not done, destructing..
NO not done, destructing..
预期输出:
copy constructor activated
done
NO not done, destructing..
NO not done, destructing.
甚至:
copy constructor activated
copy constructor activated
done
NO not done, destructing..
NO not done, destructing.
因为我从书籍和其他资源中读到,当我们按值返回函数或按值给函数提供参数时,它会调用复制构造函数,因为它会创建一个临时拷贝,而且我在主要情况下(第 6 行)复制构造函数必须被激活,但它没有..为什么?
最佳答案
根据C++标准(12.8复制和移动类对象)
31 When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.124 This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
— in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cvunqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value
— when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
请注意,在任何情况下,复制构造函数都应可用。例如,如果您将复制构造函数声明为私有(private),那么编译器将发出错误(如果它不是 MS VS 编译器:))
关于C++为什么不调用复制c'tor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30492025/