c++ - 为什么我的本地对象被破坏了两次?

标签 c++ return-value

我有一个返回本地对象的函数:

class AT
{
public:
    AT() { cout<<"construct"<<endl; }

    AT(const AT& at) { cout<<"copy"<<endl; }

    ~AT() { cout<<"destroy"<<endl; }
};

AT funcAt()
{
    AT tmp;
    return tmp;
}
...
funcAt();

输出是:

construct
copy
destroy
destroy

我想“tmp”只有construct和destroy,那为什么有copy和另一个destroy呢?复制的对象在哪里?

最佳答案

让我们充实一下:

AT funcAt()
{
    AT tmp;           [1]
    return tmp;       [2]
}                     [3]
...
funcAt();             [4]

[1]在tmp中创建一个AT对象
[2] 将tmp复制到返回值
[3] 销毁 tmp
[4] 销毁返回值,因为它没有被使用

关于c++ - 为什么我的本地对象被破坏了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6075271/

相关文章:

c++ - 迭代几个C++ vector 而没有明显地弄长它的长度

c++ - 在变量返回之前存储值

c++ - 在 C++ 中,当表达式涉及该对象时,将表达式分配给对象时是否有定义的操作顺序?

C++/Qt 全局热键

c++ - DeleteFile() 或 CopyFile() 会抛出异常吗?

c++ - 使用延迟加载加载正确的库-返回值类型错误

c - 指针或返回两个值打印

c++ - Gtkmm3 : wait for css transition to finish

java - java中ArrayList的indexOf()返回-1

ios - 如何从iOS内部返回方法对象