0

After reading this page, I already know how to implement non-copyable classes in C++.

(How do I make this C++ object non-copyable?)

Now I want implement non-copyable in C,

But I don't find similar code in C.

So I want to ask how to implement in C.

curlywei
  • 682
  • 10
  • 18
  • C and C++ are different languages, you can't implement everything from one language to the other – UnholySheep May 01 '19 at 18:58
  • 1
    C doesn't have such protection mechanism as C++. – Frankie_C May 01 '19 at 18:59
  • 1
    return a pointer on a private structure. Noone can guess the size and copy it. you have to provide functions to access to "members" too then – Jean-François Fabre May 01 '19 at 19:00
  • 5
    I feel there's an ulterior motive to this question. Why do you think you need it? I ask because C code generally deals in different idioms. – StoryTeller - Unslander Monica May 01 '19 at 19:00
  • If you can't copy it, it won't even be readable, so what use is it, unless the module where it is defined provides an interface for those operations which you allow. – Weather Vane May 01 '19 at 19:01
  • Totally different languages. Languages like C++ try to prevent the programmer from doing stupid things. C lets you do anything you want--it's up to the programmer not to do stupid things. – Lee Daniel Crocker May 01 '19 at 19:05
  • I tried to implement a singleton object in C. I think that this object is non-copyable struct. – curlywei May 01 '19 at 19:05
  • @curlywei The [singleton pattern](https://en.wikipedia.org/wiki/Singleton_pattern) is a solution in search of a problem -- it's not so much a case of object design as much as controlling how many objects you create. The answer is: Never make more than one in your code. Use `static` if you have to. – Spencer May 01 '19 at 19:08
  • @Spencer thanks! I understand! – curlywei May 01 '19 at 19:10
  • @curlywei If you post a new question that asks for what you really want, then it may be possible to get an "answer" answer, or at least be linked to a more appropriate duplicate. For example, https://stackoverflow.com/questions/8932707/what-are-anonymous-structs-and-unions-useful-for-in-c11 – Spencer May 01 '19 at 19:15

1 Answers1

4

You can do this using opaque pointers. The idea is:

  • You define a struct somewhere and you define all of its operations in terms of a pointer to that struct. That would probably be a standalone compilation unit.
  • The consumers of your struct only get a declaration but not the full definition of that struct, which means that they don't know the layout or even the size of the struct. It follows that they are able to receive, store, and pass around any pointers to that struct, but not values of it.
Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104