防止复制构造和分配返回值参考 [英] Preventing copy construction and assignment of a return value reference
问题描述
如果我有一个函数返回对我无法控制其源代码的类的实例的引用,请说list<int>
:
If I have a function that returns a reference to an instance of a class that I don't have control over its source, say list<int>
:
list<int>& f();
我想确保将其值仅分配给另一个引用,例如:
I want to ensure that its value is only assigned to another reference, e.g.:
list<int> &a_list = f();
如果用户要这样做:
list<int> a_list = f(); // note: no '&', so the list is copied
我希望它是一个编译时错误,因为用户将只操作列表的副本而不是原始列表(这绝不是我的应用程序想要/不需要的).
I want it to be a compile-time error since the user would be manipulating only a copy of the list and not the original list (which is never what is intended/wanted for my application).
在上面,有什么方法可以防止复制构造和赋值(例如通过某种包装"类)?
Is there any way to prevent copy-construction and assignment in the above (say via some kind of "wrapper" class)?
理想情况下,如果要使用某些包装类,例如wrapper<T>
,我希望它适用于任何类型T
的对象.
Ideally, if some wrapper class were to be used, say wrapper<T>
, I'd like it to work for objects of any type T
.
是的,我知道对于我可以控制的类,我可以简单地将复制构造函数和赋值运算符private
设置为:
Yes, I know that for a class that I do have control over, I can simply make the copy-constructor and assignment operator private
like:
class MyClass {
public:
// ...
private:
MyClass( MyClass const& );
MyClass operator=( MyClass const& );
};
禁止复制和转让;但是,如上所示,我想对std::list
这样做,因为我不能简单地使复制构造函数和赋值运算符private
.
to forbid copy-construction and assignment; but, as shown above, I want to do this for, say, std::list
for which I can not simply make the copy-constructor and assignment operator private
.
推荐答案
这是与我之前的答案不同的答案,因为该问题已得到澄清.我先前的答案可能对有理智要求的人有用,所以我将其保留完整.
This is a separate answer from my previous one, since the problem has been clarified. My previous answer might be useful to someone with sane requirements, so I leave it intact.
所需的行为是不可能的:请求是为了能够一般返回类似于T&
的行为,而不是类似于T
的行为.必须以某种方式使用户(和编译器!)知道该返回的东西实际上不是引用这一事实.
The desired behavior is impossible: the request is to be able to generically return something that looks exactly like a T&
but that does not behave like a T
. The fact that this returned thing is NOT actually a reference must be made known the the user (and compiler!) in some way.
这篇关于防止复制构造和分配返回值参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!