c++ - 无法解释编译器的行为

标签 c++ destructor operator-keyword

考虑这个简单的代码:

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/

相关文章:

python - 和运算符检查字符串之间的相等性

c++ - 在初始化中使用新声明的变量 (int x = x+1)?

c++ - 如果 boost::thread 创建线程失败,它会做什么?

c++ - GCC 不喜欢带有空格的 C++ 风格转换

operator-keyword - 二进制运算符 '<'不能应用于两个 'Int?'操作数

c - C 中的运算符优先级

c++ - 指针内存泄漏的可能性?

c++ - 如何在构造函数和析构函数中增加模板类中的静态 int 值?

c++ - 使用shared_ptr时需要实现析构函数、拷贝构造函数、赋值运算符

c# - 强制执行所需的函数调用