gpt4 book ai didi

c++ - RAII 在混合默认和非默认构造函数时如何工作

转载 作者:行者123 更新时间:2023-11-27 23:18:43 26 4
gpt4 key购买 nike

我想围绕使用 malloc/free 的 C 库编写一个库包装类 (LibWrap)。为此,我想使用 C++ 的 RAII 来分配和释放内存。我使用 lib_address 作为我将从图书馆收到的随机示例地址。但是,在定义我的 memeber 变量时,以某种方式调用的析构函数具有此 lib_address。

我希望默认构造函数创建的成员变量的析构函数不知道我放入替换成员变量的构造函数的新地址。

#include <stdlib.h>
#include <iostream>
using namespace std;

class LibWrap
{
int j;
int lib_address;
public:
LibWrap(): //default LibWrap
j(0),
lib_address(0)
{
cout << "default LibWrap "<<j <<"\t\t"<<lib_address << "\t" << this<<endl;
}

LibWrap(int f_j): //special LibWrap
j(0),
lib_address(0)
{
j = f_j;
lib_address = rand();
cout << "special LibWrap " << j<<"\t"<< lib_address<< "\t" << this <<endl;
}

~LibWrap()
{
cout << "killing LibWrap " << j<<"\t" <<lib_address <<"\t" << this<< endl;
}

int g()
{
return j;
}
};

class A
{
int i;
LibWrap b;

public:
A(): //default A
i(0)
{
cout << "default A\t"<<i << endl;
}

A(int f_i)://special A
i(0)
{
i = f_i;
cout << "special A\t"<<i << endl;
b = LibWrap(10);
}
~A()
{
cout << "killing A\t"<<i << endl;
}


void p()
{
cout <<"Test values: "<< i<< "," << b.g() << endl;
}
};

int f()
{
//A a; a.p();
cout << "variable\t\tlib_address\treal_address" << endl;
A a = A(1);
cout << "End" << endl;
//a.p();
}

int main()
{
f();
}

运行这段代码我希望得到以下结果:

variable        lib_address real_address
default LibWrap 0 0 0xbfef2e28
special A 1
special LibWrap 10 1804289383 0xbfef2df8
killing LibWrap 10 1804289383 0xbfef2df8 --would expect kiling LibWrap 0 0 0xbfef2e28
End
killing A 1
killing LibWrap 10 1804289383 0xbfef2e28 --would expect killing LibWrap 10 1804289383 0xbfef2df8

最佳答案

b = LibWrap(10);

这不会初始化 bb 已经作为构造 A 的一部分进行了初始化。您所做的是创建一个临时的 LibWrap 并将该临时文件复制b。然后,您将销毁那个临时的 LibWrap(这是带有 lib_address 的额外析构函数调用的来源)。

临时 LibWrap 是“0xbfef2df8”地址的来源。 b 变量是“0xbfef2e28”地址。这就是您按顺序获取它们的原因。

关于c++ - RAII 在混合默认和非默认构造函数时如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14802368/

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