簡體   English   中英

C++:析構函數和指針

[英]C++ : Destructor and pointers

In my class C, there is a pointer (var_a) to a class A, so in the destructor of C, I write "delete var_a". 在 vscode 中,代碼可以工作,但不會在 main 結束后自動停止。 此外,刪除 var_a 的行以黃色突出顯示。 調試控制台打印:

Warning: Debuggee TargetArchitecture not detected, assuming x86_64.
=cmd-param-changed,param="pagination",value="off"

hpp:

#ifndef DEF_TEST4
#define DEF_TEST4

#include <iostream>
#include <string>


class A
{   public:
    A();
    A(A const& copy_a);
    virtual std::string printer();
    protected:
    std::string var;
};

class B : public A
{
    public:
    B();
    B(B const& copy_b);
    virtual std::string printer();
    protected:
    std::string var;
};

class C
{
    public:
    C(A* a);
    ~C();
    virtual A* get_a();
    protected:
    A* var_a;
};

#endif

cp:

#include "test4.hpp"


A::A() : var("a")
{}

B::B() : var("b")
{}


A::A(A const& copy_a) : var(copy_a.var)
{}

B::B(B const& copy_b) : var(copy_b.var)
{}


std::string A::printer()
{
    return var;
}

std::string B::printer()
{
    return var;
}

C::C(A* a) : var_a(a)
{}

C::~C()
{
    delete var_a;
}

A* C::get_a()
{
    return var_a;
}

主要cpp:

#include "test4.hpp"
#include "test4.cpp"
#include <typeinfo>

int main()
{
    A ca;
    B cb;
    B cb2(cb);
    C cc(&ca);
    C cc2(&cb);

    std::cout << ca.printer() << std::endl;
    std::cout << cb.printer() << std::endl;
    std::cout << cb2.printer() << std::endl;
    std::cout << cb2.A::printer() << std::endl;
    std::cout << cc.get_a()->printer() << std::endl;
    std::cout << cc2.get_a()->printer() << std::endl;
    std::cout << "type cc2.get_a() : " << &typeid(cc2.get_a()) << std::endl;
    std::cout << "type ca : " << &typeid(ca) << std::endl;
    std::cout << "type cb : " << &typeid(cb) << std::endl;

    cc.~C();

}

我想有問題,但是什么? 抱歉,英語可能不好,這不是我的母語。 謝謝你的幫助。

正如評論所暗示的,代碼中有兩個問題。

首先, cc.~C() :永遠不要顯式調用析構函數。 在某些情況下這是合適的,但在你的未來很遠。 cc超出 scope 時,編譯器將調用析構函數。 你不需要自己做。

其次,在cccc2中, var_a指向不是用new創建的 object ; 不要delete它。 只需刪除delete var_a; 來自C::~C() var_a指向的對象在 go 超出 scope 時也會被銷毀。 你不需要自己做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM