我有下面的简单程序:
#include <iostream>
class Counter
{
private:
size_t m_count;
public:
Counter() :
m_count(0)
{
std::cout << "defctor" << '\n';
}
Counter(size_t count) :
m_count(count)
{
std::cout << "ctor" << '\n';
}
~Counter() {
std::cout << "dtor" << '\n';
}
Counter(const Counter& rhs) :
m_count{0}
{
Counter temp{rhs.m_count};
std::cout << "cctor" << '\n';
std::swap(*this, temp);
}
Counter& operator=(const Counter& rhs)
{
if (this == &rhs) {
return *this;
}
Counter temp{rhs.m_count};
std::swap(*this, temp);
std::cout << "caop" << '\n';
return *this;
}
constexpr int getCount() const noexcept {
return this-> m_count;
}
};
int main() {
Counter x{1};
Counter y;
Counter z{x}; // this fails
}
我试图构建一个简单的三类规则。我在这条线上得到了 UB,Counter z{x};
它应该调用复制构造函数。输出:
ctor
defctor
ctor
cctor
ctor
cctor
ctor
cctor
ctor
cctor
ctor
cctor
ctor
cctor
ctor
cctor
ctor
cctor
ctor
cctor
ctor
cctor
ctor
cctor
ctor
cctor
ctor
然后它重复ctor\ncctor
...
自从我使用 C++ 以来已经有一段时间了。我只是找不到错误!