Is it possible to disallow taking a reference to an object

后端 未结 2 1962
星月不相逢
星月不相逢 2020-12-18 20:21

I want to do the opposite of making instances of a class noncopyable, that is, make sure that instances of a particular class can be passed only as a c

相关标签:
2条回答
  • 2020-12-18 20:37

    I dont think making operator & private is going to do it, is there a legitimate way of doing this.

    No, because the & you use in function signatures for pass-by-reference is not an operator. You're talking either about the address-of operator (unary) or bitwise-and operator (binary). So it has nothing to do with pass-by-reference.

    There's no way to disallow pass-by-reference for a type.

    I doubt your motivation is strong enough to do this, and you appear to have a bad understanding of the passing mechanism:

    If any function tries to receive it by reference, I would like it to give a compilation error (ideally) or a run time error.

    A function either passes a parameter by reference, or by value. It's decided by its declaration, and I think your confusion stems from here. For example:

    void foo(X x);
    

    takes the parameter x by value. There's no way to pass it by reference. No way. Likewise:

    void foo(X& x)
    

    takes it by reference, and it always will.

    0 讨论(0)
  • 2020-12-18 20:45

    That's impossible. Any named variable can bind to a reference variable of the appropriate type. That's just how the language works.

    In particular, you could never have a copy constructor with your restriction, so you couldn't actually pass the object by value!

    0 讨论(0)
提交回复
热议问题