在删除对象后进入析构函数之前,什么会使字段变量变得过时? 我正在寻找我在这个网站上遇到的这个问题的答案并遇到了这个: Lifetime of object is over before destructor is called?
有些事情根本没有加起来:如果我在另一个 WrapperClass
中声明了一个指向 SomeClass
的指针,当我构造 WrapperClass
时> 我需要创建一个 new SomeClass
并在包装器销毁时将其delete
。
这是有道理的,并且到目前为止一直有效。
该指针在析构函数中仍然有效并且正确无误,否则显然我无法删除它。
现在我的问题是,当我调用析构函数时,WrapperClass
的字段成员(一个 int 和一个指向 SomeClass
数组的指针)都是垃圾。我在构建后检查了包装器对象,数据很好。包装器实际上是另一个 Main
类中的指针,当我破坏那个 Main
(它破坏了包装器)但如果我只是 delete< 就可以正常工作
Main
中另一个方法的包装器。
我的偏执使我得到了上面提到的答案,现在我完全困惑了。
有人愿意了解这里到底发生了什么吗?
编辑:
Node
是 SomeClass
。
class WrapperException{};
class Wrapper {
private:
struct Node { /*....*/ };
int numNodes;
Node** nodes;
public:
Wrapper() : numNodes(0) { nodes = new Node*[SIZE]; }
Wrapper(const Wrapper& other) { throw WrapperException(); }
Wrapper& operator=(const Wrapper& other) { throw WrapperException(); }
~Wrapper() { //calling delete Main gets me here with garbage for numNodes and nodes
for(int i = 0; i < numNodes; i++)
delete nodes[i];
delete nodes;
}
};
class MainException{};
class Main {
public:
Main() { wrapper = new Wrapper(); }
Main(const Main& other) { throw MainException(); }
Main& operator=(const Main& other) { throw MainException(); }
~Main() { delete wrapper; }
private:
Wrapper* wrapper;
};
最佳答案
您需要使用标准库来实现此行为。
class Wrapper {
private:
struct Node { /*....*/ };
int numNodes;
std::vector<std::unique_ptr<Node>> nodes;
public:
Wrapper() : numNodes(0) { nodes.resize(SIZE); }
// No explicit destructor required
// Correct copy semantics also implemented automatically
};
class Main {
public:
Main() : wrapper(new Wrapper()) {}
// Again, no explicit destructor required
// Copying banned for move-only class, so compiler tells you
// if you try to copy it when you can't.
private:
std::unique_ptr<Wrapper> wrapper;
};
此代码保证正确执行。在 C++ 中,如果您使用了 new[]
、delete
或 delete[]
,请立即重构您的代码以删除它们,并查看非放置 new
的任何使用的三倍 - 构造 unique_ptr
几乎是唯一有效的情况。这不过是手动内存管理的常见预期结果。
关于c++ - 在调用实际析构函数之前删除了字段变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806244/