gpt4 book ai didi

c++ - C++-通过在* this指针上使用new放置引起的内存泄漏?

转载 作者:行者123 更新时间:2023-12-02 09:48:03 24 4
gpt4 key购买 nike

众所周知,placement new只是在不分配任何内存的情况下构造了一个对象。同样,Resource类中的所有成员都是对象而不是指针,尽管std::string内部拥有一个动态数组,当std::string对象被破坏时,该数组将被释放。 *this指向分配在堆栈上的内存,这意味着将始终调用析构函数。因此,我认为new这里所做的只是覆盖原始对象。这是一个简单的例子。在运行此示例时(在VS 2019上),内存使用量一直在上升。

class Resource
{
public:
Resource() {};
Resource(const std::string& s) : str(s)
{
new(this)Resource();
}


private:
std::string str;

};


int main()
{
while (true)
Resource resource("hello");
}

最佳答案

标准(最新草案)说:

[basic.life]

A program may end the lifetime of any object by reusing the storage which the object occupies ... if there is no explicit call to the destructor or if a delete-expression is not used to release the storage, the destructor is not implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.


因此,由于构造函数为动态对象 重用了*this的存储,而没有调用原始对象的析构函数,因此永远不会调用该析构函数。该析构函数将销毁字符串成员并释放其内存。

结论:不要通过 *this进行新的放置。

关于c++ - C++-通过在* this指针上使用new放置引起的内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63467648/

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