考虑这个简单的代码:
class A {
public:
int value;
A(int value) { this->value = value; }
~A() { printf("destroying %d\n", value); }
A operator ++() { return A(value + 1); }
};
int main() {
A a(1);
printf("before increment: %d\n", a.value);
a = ++a;
printf("after increment: %d\n", a.value);
return 0;
}
这个输出:
before increment: 1
destroying 2
after increment: 2
destroying 2
为什么a
的值在被销毁前多了1?
最佳答案
在 operator++ 方法中,您创建临时 A 对象,然后当您从函数返回它时将其销毁。 应该还有另一个复制构造和销毁,但是RVO省略了这个。
当您将日志添加到构造函数时,您也会更好地了解正在发生的事情。我还允许自己将 printf 更改为 cout,以获得更多 c++ 风格的编码风格。
#include <iostream>
class A {
public:
int value;
A(int value) {
std::cout << "creating " << value << std::endl;
this->value = value;
}
~A() {
std::cout << "destroying " << value << std::endl;
}
A operator ++() { return A(value + 1); }
};
int main() {
A a(1);
std::cout << "before increment: " << a.value << std::endl;
a = ++a;
std::cout << "after increment: " << a.value << std::endl;
return 0;
}
输出:
creating 1
before increment: 1
creating 2
destroying 2
after increment: 2
destroying 2
您还可以阅读有关运算符重载的规范实现:
http://en.cppreference.com/w/cpp/language/operators
operator++ 重载应该是这样的:
struct X
{
X& operator++() // prefix version
{
// actual increment takes place here
return *this;
}
X operator++(int) // postfix version
{
X tmp(*this); // copy
operator++(); // pre-increment
return tmp; // return old value
}
};
关于c++ - 无法解释编译器的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37243237/