问题描述
我想做一个相反的事情,使一个类的实例不可复制
,即确保一个特定类的实例只能被传递作为副本,而不作为参考。如果有任何函数试图通过引用接收它,我希望它给出一个编译错误(理想情况下)或运行时错误。
我不认为制作 operator&
private会这样做,是否有合法的方法。
否,因为& ;
在函数签名中用于通过引用的不是操作员。您是在谈论地址运算符(一元)或按位与运算符(二进制)。因此,它与传递引用无关。
无法禁止类型的传递引用。 / p>
我怀疑您的动机是否足够强大,并且您似乎对传递机制缺乏理解:
一个函数通过引用或值传递参数。它由声明决定,我想您的困惑源于此。例如:
void foo(X x);
采用值 x
。无法通过引用传递它。没门。同样:
void foo(X& x)
将其作为参考,并且始终如此。
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 copy and not as a reference. If any function tries to receive it by reference, I would like it to give a compilation error (ideally) or a run time error.
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:
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.
这篇关于是否有可能不允许引用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!