Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

6
  • p.s. there are no constructors per se in C; only in C++. In C, your data structure would simply be copied byte-for-byte. Commented Apr 18, 2013 at 22:26
  • @EdwardFalk: of course, in facts I talked about initialization, not construction; also, the "byte-for-byte" thing is not specified by the standard, which actually says that only the named fields are guaranteed to be copied ("Unnamed members of structure objects have indeterminate value even after initialization.", C99 §6.7.8 ¶9) - i.e., the padding may or may not be copied. Commented Apr 18, 2013 at 22:31
  • Great explanation, I am guessing you cannot override the default behavior to perform a deep copy if that was required? Commented Apr 18, 2013 at 22:37
  • 1
    @chrisw69: you can in C++ by providing your custom copy constructor; it is done routinely, e.g. in the standard library containers (std::vector, ...). In C, instead, there's no automatic mechanism, you have to provide your own functions (to be invoked manually) to perform a deep copy. By the way, by some this is seen as an advantage, since the "deep copy by default" policy of some objects, if not well understood, can give considerable slowdowns. Compare with Java or C#, where an object is passed by reference by default, but can optionally provide a Clone method to perform a deep copy. Commented Apr 18, 2013 at 22:52
  • I believe in C# and java, object references are passed by value; the ref keyword passes the object by reference, which, as far as I am aware, would be the same as passing a pointer to a pointer in a language like C or C++. As far as Clone goes, I think the ICloneable interface is not recommended as it doesn't specify whether or not the clone is deep or shallow. stackoverflow.com/questions/536349/why-no-icloneablet Commented Apr 18, 2013 at 23:02