Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

c++ - Is it possible to disallow taking a reference to an object

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...