Adding a field to a structure without breaking existing code

So, I am working with this huge repository of code and realized that one of the structures lacks an important area. I looked at the code (which uses the structure) as closely as I could, and came to the conclusion that adding an extra field would not break it.

Any ideas on where I could squint?

Also: design advice is welcome - how best can I do this?

For example (if I did not understand):

typedef struct foo
{
  int a;
  int b;
}
foo;

Now he:

typedef struct foo
{
  int a;
  int b;
  int c;
}
foo;
+3
source share
10 answers

From what you wrote above, I see nothing wrong. Two things I can think of:

  • , , "" . , , , .
  • , c , ?

Follow Up:

, . - , - . , , . ? , , 0% , , . ?

+4

/ , .

, .

+6

sizeof (struct) ​​ , → . , , - . , , , .

+4

, ?

. . , , .

, , , POD C-style, , . , - , ( , ) , , . ++, POD /ctors .., . - , ..

+2

memcpy, memset, memcmp. . , .

struct. , . , #define typedef, .

+1

++:

Pimpl/d-Pointer - , .

,

// foo.h
class Foo {
public:
    Foo();
    Foo(const Foo &);
    ~Foo();
    int a() const;
    void a(int);
    int b() const;
    void b(int);
private:
    class FooPrivate *const d;
};

// foo.c
class FooPrivate {
public:
    FooPrivate() : a(0), b(0) {}
    FooPrivate(const FooPrivate &o) : a(o.a), b(o.b) {}
    int a;
    int b;
};
Foo::Foo() : d(new FooPrivate()) {}
Foo::Foo(const Foo &o) : d(new FooPrivate(*o->d)) {}
Foo::~Foo() { delete d; }
int Foo::a() const { return d->a; }
void Foo::a(int a) { d->a = a; }
// ...

// foo.h
class Foo {
public:
    // ...
    int a() const;
    void a(int);
    int b() const;
    void b(int);
    int c() const;
    void c(int);
    // ...
};

// foo.c
class FooPrivate {
    // ...
    int a;
    int b;
    int c;
};
// ...

(!) Foo.

+1

, ( ;))

, 'c' , , , ? c foo , , foo c. , .

, - , , , - sizeof() -.

+1

, .

0

-, , - , undefined, . , , - ( ), . , undefined : " , ", , , ( IO).

, , typedef FOO... struct FOO, - C ++. , :)

0

It is always safe to add new elements at the end of structure C. An event if this structure is passed on to various processes. The code that was recompiled will see the new member of the structure, and the code that was not just will know about the size of the old structure and just read the old members that he knows about. Here it is necessary to indicate that a new member should be added at the end of the structure, and not in the middle.

0
source

Source: https://habr.com/ru/post/1729407/


All Articles