1

I'm pretty new in C and would like to ask a question about copying behavior. I'm reading Scott Meyers' C++ and he said in the book that C++ may be considered as a composition of languages and we should distinguish the so called C part from the C++ part. Now if we have to use some native C API containing the following:

FontHandle getFont(); //From, C API

void releaseFont(FontHandle fh); //From the same C API

As far as I know, the C language doesn't allow defining a custom copying behavior via copy-custructors. So, what should I expect to happen if I write the following:

FontHandle f1 = getFont();
FontHandle f2 = f1; //What's going to happen here? Deep or shallow copy?
stella
  • 2,546
  • 2
  • 18
  • 33
  • `FontHandle` is presumably a `typedef` of a pointer or integer type, what do you think happens when you say `char* a; char* b = a;`? – user657267 Sep 29 '15 at 04:09
  • If this is C API, then of course shallow copy. `FontHandle` is likely `typedef`'ed as `int` or `void*` or something similar. Merely assigning a handle can't possibly clone the underlying font object, if that's what you are asking. You'll just end up with two variables holding the same numerical value. – Igor Tandetnik Sep 29 '15 at 04:09
  • This may be the answer. http://stackoverflow.com/a/9127315/1099230 – luoluo Sep 29 '15 at 04:11
  • @IgorTandetnik Do you mean that if we have a pointer to type in C, e.g. `char* a;` and then wrtie `char *b = a`, we'll have `b` is a copy of `a`. But what if we have `char a = 'a'; char b = a;`? How will the copying be performed then? – stella Sep 29 '15 at 04:14
  • The same way - `b` is a copy of `a`. I'm not sure I quite grasp the nature of your confusion. – Igor Tandetnik Sep 29 '15 at 04:20
  • @IgorTandetnik In short, C simply copies the underlying memory of a variable, is that right? – stella Sep 29 '15 at 04:23
  • If the two are of the same type, yes. – Igor Tandetnik Sep 29 '15 at 04:23

2 Answers2

3

C will always do a 'shallow' copy. If the variable is a pointer, the value will be copied. If the variable is a struct, the struct's contents will be copied (if the contents happens to include pointers, their values will simply copied like everything else).

andars
  • 1,384
  • 7
  • 12
  • If the variable a primitive like `char`? – stella Sep 29 '15 at 04:15
  • The value will simply be copied. No matter what the variable is, C will simply copy the memory backing that variable from one place to another. – andars Sep 29 '15 at 04:17
0

if the object FontHandle define a correct copy constructor or provide correct implementation of operator= then you will have the deep copy (object copied correctly)

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93