gpt4 book ai didi

C++: STL: vector: remove: 析构函数调用

转载 作者:太空狗 更新时间:2023-10-29 23:31:08 27 4
gpt4 key购买 nike

代码如下:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct A {
A(int i = -1): i_(i) {
wcout << "Constructor: i = " << i_ << endl;
}
A(A const &a) {
wcout << "Copy constructor: i = " << i_ << " a.i = " << a.i_ << endl;
*this = a;
}
~A() { wcout << "Destructor: i = " << i_ << endl; }
A &operator=(A const& a) {
wcout << "Copy assignment operator: i = " << i_ << " a.i = " << a.i_ << endl;
i_ = a.i_;
return *this;
}
bool operator==(A const& rhs) { return i_ == rhs.i_; }
int get() { return i_; }
private:
int i_;
};

int wmain() {
A a[] = {1, 2, 3, 2, 4, 5};
vector<A> v(a, a + sizeof a/sizeof a[0]);
wcout << "==== Just before remove ====" << endl;
remove(v.begin(), v.end(), 2);
wcout << "==== Just after remove ====" << endl;

return 0;
}

输出:

==== Just before remove ====
Constructor: i = 2
Destructor: i = 2
Constructor: i = 2
Destructor: i = 2
Constructor: i = 2
Destructor: i = 2
Copy assignment operator: i = 2 a.i = 3
Constructor: i = 2
Destructor: i = 2
Constructor: i = 2
Destructor: i = 2
Copy assignment operator: i = 3 a.i = 4
Constructor: i = 2
Destructor: i = 2
Copy assignment operator: i = 2 a.i = 5
==== Just after remove ====

问题是:为什么在运行 remove() 时调用了 6 次析构函数?我需要澄清这个困惑。

注意:请在您的系统上执行此代码,然后再回答。注意:MSVCPP 11

最佳答案

The question is: why destructor is called 6 times while remove() was running?

总而言之,析构函数调用与 2 通过 remove() 隐式转换为 A 有关。每当这种隐式转换的结果超出范围时,A 的析构函数就会被调用。

这些隐式转换的原因是 remove() 需要将 a 的每个元素与 2 进行比较。唯一的方法是调用 A::operator==(const A&):

  bool operator==(A const& rhs) { ... }

由于 rhsconst A& 类型,编译器:

  1. 调用A(int)2转换为A
  2. 调用operator==(const A&);
  3. 调用 A::~A() 来销毁临时文件。

后者是您看到的析构函数调用。

如果您要将以下比较运算符添加到 A,您会看到那些析构函数调用消失了:

  bool operator==(int rhs) { return i_ == rhs; }

或者,如果您像这样调用 remove(),您会看到所有除第一个析构函数调用外的都消失了:

remove( v.begin(), v.end(), A(2) );

最后,如果你要使 A::A(int) explicit,编译器将不允许你调用 remove()2 作为最后一个参数(您必须使用 A(2) 调用它)。

关于C++: STL: vector: remove: 析构函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8895563/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com