【问题标题】:Why is the constructor/destructor called once? [duplicate]为什么构造函数/析构函数被调用一次? [复制]
【发布时间】:2015-04-28 06:43:52
【问题描述】:

这是我的源代码:

#include <iostream>
#include <memory>
#include <vector>

using namespace std;

class Copy {
public:

    Copy() {
        cout << "Constructor called" << endl;
    };

    Copy(const Copy& copy) {
        cout << "Copy constructor called" << endl;
    }

    Copy& operator=(Copy copy) {
        cout << "Copy-Assign constructor called" << endl;
        return *this;
    }

    Copy(Copy &&copy) noexcept {
        cout << "Move constructor called" << endl;
    }

    Copy& operator=(Copy &&copy) noexcept {
        cout << "Move-Assign constructor called" << endl;
        return *this;
    }

    ~Copy() {
        cout << "Destructor called" << endl;
    }
};

Copy TestCopy() {
    Copy cop;
    return cop;
}

vector<Copy> TestCopyVector() {
    vector<Copy> copyVector = vector<Copy>{Copy()};
    return copyVector;
}

int main()
{
    Copy cop = TestCopy();
    //TestCopy();
    //vector<Copy> copyVector = TestCopyVector();

    return 0;
}

在我的理解中

Copy cop = TestCopy();

应该调用 Copy 的 move-assignment。虽然输出如下:

$ ./test 
Constructor called
Destructor called

有人能帮忙解释一下吗?谢谢。

【问题讨论】:

  • Copy cop = TestCopy(); 无论如何都不会调用移动赋值 - 此行中没有赋值。在没有省略的情况下,它将调用移动构造函数。

标签: c++ c++11 constructor destructor


【解决方案1】:

它被称为RVO (Return value optimization),这是一个众所周知的优化,允许编译器在类似情况下进行。

【讨论】:

    猜你喜欢
    • 2022-07-05
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    相关资源
    最近更新 更多