我对大多数OO理论有了深刻的理解,但让我困惑的一件事是虚拟析构函数.
我认为无论什么以及链中的每个对象,析构函数总是会被调用.
你什么时候打算让它们成为虚拟的?为什么?
我知道在C++中为基类声明虚拟析构函数是一个好习惯,但是virtual即使对于作为接口的抽象类来说,声明析构函数总是很重要吗?请提供一些理由和示例原因.
是否有充分的理由不为类声明虚拟析构函数?什么时候应该特别避免写一个?
我知道这并std::unique_ptr不能保证内存安全,尤其是在循环依赖的情况下。然而,就我而言,我看不到它。Child包含Parent(或者SecondChild在多态性的情况下),但它们都不包含Child.
Valgrind 报告4 bytes丢失,所以我认为它SecondChild没有被破坏。我的代码确实依赖于多态性,因此我希望获得有关重构的建议,这些建议不会Parent*在Child.
#include <iostream>
#include <memory>
using namespace std;
struct Parent
{
    Parent() {
        cout << "Expr created" << endl;
    }
    ~Parent() {
        cout << "Expr destroyed" << endl;
    }
};
struct Child : public Parent 
{
    std::unique_ptr<Parent> content;
};
struct SecondChild : public Parent 
{
    int val;
};
std::unique_ptr<Parent> foo()
{
    auto test = make_unique<Child>();
    auto content_in_child = make_unique<SecondChild>(); …在Delphi应用程序中创建自定义类时,我使用标准过程:
TCustomClass = Class
 private
  var1,var2 : integer/string/Real/Boolean...
  procedure P1...
  function F1...
 public
  constructor Create;
end;
...
CustomClass := TCustomClass.create;
我想知道我是否还必须同时创建Destructor过程,或者在应用程序关闭时资源会自动释放吗?
我总是使用Application作为所有者,很少使用Self或Nil,而且我不记得我见过有人在我在Internet上看到的类中声明Destructor,除了有人使用指针的情况。
如下所述,Delphi中的析构函数背后的逻辑是否与C ++中的相同:
提前致谢。
EDIT1:正如Free Consulting所述,我忘记说变量之一可能是TBitmap类型
在delegate模式中,destuctor虚拟化是好的吗?
class MyClass
{
    ...
};
class MyClassDelegate
{
    ...
};
一方面类MyClassDelegate是一个接口,应该是从继承,但另一方面它不应该delete在subclass通过MyClassDelegate指针
你怎么看 ?
当使用工厂创建对象时,例如在下面的示例中,在某些情况下,shared_ptr显然被返回过程中被删除的对象被删除(在调试期间,对象被创建好,但是当它被分配给this->xs异常时被抛出) .当我更改工厂方法以返回原始指针时,作为代码的Link::xs成员unique_ptr运行正常.幕后发生了什么shared_ptr导致它以这种方式行事?它与shared_ptr<CrossSection>包裹Circular物体的事实有关吗?使用MS Visual C++ 2012进行了测试.
class Link
{
private:
    std::shared_ptr<xs::CrossSection> xs;
public:
    void parseXsection(const std::vector<std::string>& parts);
    std::shared_ptr<xs::CrossSection> getXs() { return this->xs; }
};
void Link::parseXsection(const std::vector<std::string>& parts)
{
    this->xs = xs::Factory::create(parts[1]);
}
namespace xs
{
    class CrossSection
    {
    };
    class Circular : public CrossSection
    {
    };
    class Dummy : public CrossSection
    {
    };
    class Factory
    {
    public:
        static std::shared_ptr<CrossSection> create(const std::string& type);
    };
    std::shared_ptr<CrossSection> Factory::create(const std::string& …c++ ×6
inheritance ×2
polymorphism ×2
shared-ptr ×2
class ×1
delegates ×1
delphi ×1
destructor ×1
memory-leaks ×1
oop ×1
unique-ptr ×1
visual-c++ ×1