4

Is there any GCC warning that cautions when I try to copy structures containing pointers with assignment operator instead of deep copying?

8
  • In recent versions of GCC, you can use gcc --help=warnings to get all the warnings listed. Commented Nov 30, 2012 at 7:30
  • 2
    -Wall gives a selection of the most useful warnings; it does not give you all warnings. Neither does -Wall -Wextra; there are esoteric warnings that are not triggered by either of these. Commented Nov 30, 2012 at 7:37
  • @EvanLi That's still wrong. Commented Nov 30, 2012 at 7:38
  • For what it is worth: to copy a struct with plain assignment should never be done without knowing and considering all members of the struct. Whenever you consider such an assignment, warning bells should appear inside your head, before you even get as far as compiling. Commented Nov 30, 2012 at 7:41
  • Thanks to @JonathanLeffler. I learned. Commented Nov 30, 2012 at 7:43

2 Answers 2

4

The answer is no. See the list of gcc warning options.

Given the same page, warnings are:

Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error.

And shallow copy instead of a deep copy is neither risky nor erroneous as it may be an intended behavior. So there is no reason for such warning option to exist.

What you may want is a static analyzer such as clang's one, though in my knowledge this one doesn't offer that kind of functionality.

Sign up to request clarification or add additional context in comments.

Comments

1

I remember seeing precisely such a warning with -Weffc++

Of course, you'd have to be willing to compile in c++ mode. (See below)

Edit I tested it: Sadly, this won't warn about POD (i.e.) C types. Here is the test:

struct HasPointer { int* resource; HasPointer() {}; ~HasPointer() {}; }; 

Compiled with

E:\mingw64>g++ test.c -Weffc++ 

Outputs

test.c:1:8: warning: 'struct HasPointer' has pointer data members [-Weffc++] struct HasPointer ^ test.c:1:8: warning: but does not override 'HasPointer(const HasPointer&)' [-Weffc++] test.c:1:8: warning: or 'operator=(const HasPointer&)' [-Weffc++] test.c: In constructor 'HasPointer::HasPointer()': 

But leaving the ctor/dtor out, the warning isn't even emitted, so this option doesn't work for your code, even in C++ compile mode.


Compiling C code in C++ mode:

(Use extern "C") to achieve binary interoperability. It is usually as simple as

extern "C" { # include "my.h" # include "stuff.h" // ... } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.