简体   繁体   English

返回参考且仅参考

[英]Returning a reference and only a reference

I have the following function which is part of a Grid class: 我有以下函数,它是Grid类的一部分:

T& select(unsigned int x, unsigned int y)
{
    return nodes[x + width * y].element;
}

Is there any way I can force the compiler to reject construction of a T from returned T& without deleting the copy constructor of T (which might not even be a class)? 有什么办法可以迫使编译器在不删除T&的副本构造函数(甚至可能不是一个类)的情况下,从返回的T&拒绝T的构造?

auto n = grid.select(1,1); // this should be illegal

While you return a reference, what users of the code do with it later is entirely out of your control. 当您返回引用时,代码的用户以后如何使用它完全不受您的控制。 The fact that they can use your reference to create a copy is valid in the language. 他们可以使用您的参考来创建副本这一事实在该语言中是有效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM