gpt4 book ai didi

c++ - 不在 C++ 中调用默认构造函数

转载 作者:太空宇宙 更新时间:2023-11-04 15:56:48 25 4
gpt4 key购买 nike

<分区>

在下面的代码中,我使用无法理解的调试器进行跟踪
1. 为什么 B b2() 从未被调用而是被跳过。
2. 为什么auto_ptr只在创建的对象被派生(B)时才调用base(A)析构函数?

class A {
public:
A(int x_) : _x(x_) {cout << "A::A( " << _x << ")" << std::endl; }
A(const A& src) : _x(src._x) {cout << "A::A(copy " << _x << ")";}
~A() { std::cout << "A::~A " << std::endl; }
int x() const { return _x; };
protected:
int _x;
};
class B : public A {
public:
B():A(0) {cout << "B::B( " << _x << ")";}
B(A a):A(a.x()) {cout << "B::B(A) ";}
~B() { std::cout << "B::~B "; }
};
int main() {
B b1(11); //which calls A(int) -> B(A a) -> {A::x() -> A(int)} -> ~A()}
B b2(); //It's never called, why?
std::auto_ptr<A> aptr(new B); //Calls A(0)->B()-> ~A() ==> why ~A() only but not ~B() ?
}
/*Actual Result:
B b1(11) => It prints following
A::A(11)
A::A(11)
B::B(A)
A::~A
/// Why B b2() is not called???
auto_ptr<A> aptr(new B) => It prints following. Why ~B() is not called?
A::A(0)
B::B(0)
A::~A
B b1(11) destructors => It prints following
B::~B
A::~A */

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