Comments (4)
以下描述貌似和上文相悖:
析构函数一般用来释放对象所分配的资源。例如,
string
的构造函数(以及其他string
成员)会分配内存来保存构成string
的字符。string
的析构函数就负责释放这些内存。类似的,vector
的若干操作都会分配内存来保存其元素。vector
的析构函数就负责销毁这些元素,并`释放它们所占用的内存。 引用自《C++ Primer》第 402 页
string
、vector
是容器,它们的构造、析构中是妥妥的动态分配内存、释放内存的。
from quote-demo.
其实给我带来惊讶的是跳出自己思维盲区的一个操作:竟然还可以显式地调用析构函数。
显式调用构造函数也是可以的。
https://blog.csdn.net/jnu_simba/article/details/8803377
from quote-demo.
“显式调用析构函数并不释放内存” 标题给人误解:不显式调用析构函数就会释放内存似的。实际上正如前文描述,析构只负责销毁对象(有时会包含「释放动态申请的内存」任务),虽然和内存释放组合在一起,但释放内存并不是由析构函数带来的。
from quote-demo.
显式析构带来的直接影响就是二次析构,具体是否会带来不良影响需要看具体的业务逻辑。
void test()
{
auto ptr = new Person(1);
ptr->~Person();
ptr->echo();
delete ptr;
}
void test2()
{
Person ins(33);
ins.echo();
ins.~Person();
//ins.echo();
}
最可能的负面影响就是当析构中释放动态内存时,如果未作判断直接释放就会抛出堆异常。
Person::~Person()
{
cout << "~Person" << endl;
//if (p)
{
delete p;
//p = nullptr;
}
}
from quote-demo.
Related Issues (18)
- 合并 testinstall[d] 两个目录
- 合并 debug & release
- 将 grpc 作为第三方库纳入项目管理
- 文件包含不能在当前代码页(936)中表示的字符 HOT 5
- 依赖路径未同步修改
- powershell 和 cmd
- crlf 或者 lf 格式源生成的文件是完全相同的吧?
- 再次编译 grpc HOT 3
- 学习 add_subdirectory 以及 ExternalProject_Add
- node.js 的例子并不是都能跑通
- client 增加 Credentials plugin,server 怎么处理?
- 依赖库,他妈怎么回事? HOT 7
- 为什么会出现 C2 错误?
- grpc_unsecure.lib 和 ${_GRPC_GRPCPP_UNSECURE} 并不相同
- 有且仅有一个虚函数的基类是否都应该用 std::function<> 替换?
- Observer 观察者模式的具体实现,运行不起来吧?
- 主动对象,是什么概念?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from quote-demo.