如何在C中使用仿析构函数方法?

问题描述 投票:-1回答:1

[当我在GrandParent_dtor中使用Parent_dtor时,我没有遇到任何失败,但是当我在Parent_dtor中尝试使用Child_dtor并运行makefile命令时。我知道了recipe for target 'run' failed。我不知道也许我使用了不正确的free()方法。

// parent.h
#include "child.h"

typedef struct Parent{
    Child *var;
} Parent;

Parent *Parent_ctor();
void Parent_dtor(Parent*);
// parent.c
#include "parent.h"

Parent *Parent_ctor(){
    Parent *self = malloc(sizeof(Parent));
    self->child = Child_ctor();
    return self;
}
void Parent_dtor(Parent *self){
    Child_dtor(self->child); // if i take this in comment, it runs without failed
    free(self);
}
// child.h
typedef struct Child{
    const char *var;
} Child;

Child *Child_ctor();
void Child_dtor(Child*);
// child.c
#include "child.h"

Parent *Child_ctor(){
    Child *self = malloc(sizeof(Child));
    self->var = "blabla";
    return self;
}
void Child_dtor(Child *self){
    free(self);
}

makefile的示例:

all: compile run
compile:
    gcc -I ./include/ -o ./lib/GrandParent.o -c ./src/GrandParent.c
    gcc -I ./include/ -o ./lib/Parent.o -c ./src/Parent.c
    gcc -I ./include/ -o ./lib/Child.o -c ./src/Child.c
    gcc -I ./include/ -o ./bin/main ./lib/GrandParent.o ./lib/Parent.o ./lib/Child.o ./src/main.c

run:
    ./bin/main
c makefile
1个回答
0
投票

具有parent.h

typedef struct Parent{
   Child *var;
} Parent;

您不能编译Parent.c

Parent *Parent_ctor(){
   Parent *self = malloc(sizeof(Parent));
   self->child = Child_ctor();
   return self;
}
void Parent_dtor(Parent *self){
   Child_dtor(self->child); // if i take this in comment, it runs without failed
   free(self);
}

使用child而不是var,重新定义struct具有:

似乎是合理的
 typedef struct Parent{
    Child *child;
} Parent;

在child.h中,您有

Child *Child_ctor();

但是在Child.c中,您有:

Parent *Child_ctor(){

必须是

Child *Child_ctor(){
© www.soinside.com 2019 - 2024. All rights reserved.