C++ 中的引用和析构函数
reference and destructor in c++
我有以下类:
class A
{
public:
B& getB() {return b;}
private:
B b;
};
class B
{
~B() {cout<<"destructor B is called";}
...
};
void func()
{
A *a = new a;
B b = a->getB();
.....
}
为什么在退出函数函数时调用类 B 的析构函数?是否让函数 getB 返回对对象 B 的引用?如果类 A 在函数函数的末尾仍然存在,为什么调用 B 的析构函数?
B b = a->getB();
将调用复制构造函数B(const& B)
因此您在堆栈上创建一个新对象,其中包含引用返回的对象的副本。请改用:
B& b = a->getB();
并且不会调用析构函数,因为您不会创建新的 B 对象
当你有:
B b = a->getB();
从对 B
的现有实例 (B&
) 的引用创建类型 B
的新对象。这里调用的不是B::operator=
,而是复制构造函数。
每个类都有一个复制构造函数(如果不显式添加它,编译器将为你提供一个)。它接受单个参数,该参数是对同一类的引用。您尚未将复制构造函数放入上面的代码中,因此我假设编译器已为您生成了一个:
class B
{
public:
B(B& other)
{
// memberwise copy (shallow copy)
};
};
因此,A::getB()
返回了对成员A::b
的引用,并将此引用作为参数传递给B::B(B&)
。
void func()
{
A *a = new A(); // Instance of A is created on the heap;
// (pointer a is a local variable and is on the stack though!)
// A::b is object of type B and it is on the heap as well
B b = a->getB(); // Instance of class B is created on the stack (local variable)
.....
delete a; // deleting A from the heap:
// A::~A is called which calls B::~B (of its member b)
} // a and b go out of the scope; b is an object => B::~B is called
相关文章:
- 通过引用传递-为什么要调用这个析构函数
- 对具有动态分配的内存和析构函数的类对象的引用
- 对已定义的接口析构函数的未定义引用
- 对 clang 中析构函数的未定义引用
- 如果引用应该保留,不删除析构函数中的指针会导致内存泄漏吗?
- C++析构函数通过引用
- 在析构函数内取消引用指针时出现分段错误
- 为什么可以从常量引用调用析构函数
- 为什么在调用析构函数后仍然可以引用堆分配的对象
- 当通过引用传递包含指针成员的类对象时,为什么要多次调用析构函数?我该如何更正
- 通过值或引用调用时未调用构造函数/析构函数.不管怎样
- 引用的临时对象的析构函数
- g++对基类析构函数和派生类指针的未定义引用
- C++虚拟析构函数和符号引用错误
- C++对共享库中类的构造函数和析构函数的未定义引用错误
- 我是否正确构建了这些引用和指针函数?如果是,我该如何显式调用我的析构函数
- 从静态变量引用非静态变量会使非静态变量先于静态变量进行析构函数
- 具有内联析构函数的未定义引用
- 为什么析构函数在对象引用作为参数传递时函数范围结束后调用
- C++ 中的引用和析构函数