初始化引用时避免按值复制
我有一个函数接口:
struct iFace {
virtual Type& getType() = 0;
}
并且想法是像这样检索它:
iFace& iface = getIface();
Type& type = iface.getType();
但是,我偶尔会犯一个错误并写道:
Type type = iface.getType();
它按值复制,这是我想避免的。然而,当我犯这样的错误时,编译器不会发出警告,因为它的语法合法。我想为此触发编译时错误,问题我的替代方案是什么?
我考虑过声明一个复制构造函数,但不在任何地方定义它,如果使用它,会导致链接时错误,但随后我将无法在任何情况下使用复制构造函数,这小于理想的
I have a function interface:
struct iFace {
virtual Type& getType() = 0;
}
and the idea is to retrieve it like:
iFace& iface = getIface();
Type& type = iface.getType();
however, i occassionally i do a mistake and write:
Type type = iface.getType();
which copies by value, which is what i want to avoid. However when i make such mistakes, the compiler doesn't issue a warning because its legal syntax. I would like to trigger a compile-time error for this, Question what are my alternatives?
i thought about declaring a copy constructor but not defining it anywhere, causing a link-time error if it's used, but then i won't be able to use copy constructor in ANY situation, which is less than desiderable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将复制构造函数和赋值运算符置于“private”下,使 iFace 不可复制。然后提供显式的 Copy 方法。
您还可以使用 boost noncopyable 来执行相同的操作(其如上所述实施)。
因此,如果您希望复制代码,您会这样做
作为旁白 - 我想补充一点,如果您出于性能问题而这样做,您确定优化器不会为您删除临时副本吗?
Make iFace noncopyable by putting the copy constructor and assignment operator under "private". Then provide an explicit Copy method.
You can also use boost noncopyable to do the same thing (its implemented as above).
So if you wanted your code to copy, you would do
As an aside -- I'd add that if you're doing this because of performance concerns, are you certain the optimizer doesn't get rid of the temporary copy for you?
在这里返回一个指针似乎是合理的,但是如果您担心所有权混乱,您可以返回引用周围的包装器。
原始类可以照常复制,但您必须显式地进行引用。我对这个想法并不热衷(我认为一个没有意识到复制语义如何工作的用户比一个不小心持有其中一个太长时间的用户更重要)但理论上它是可行的。
Returning a pointer seems reasonable here, but if confusing ownership worries you you could return a wrapper around the reference.
The original class can copy as normal, but the reference you have to do explicitely. I'm not enthusiastic about the idea (I would think less of a user who didn't realize how copy semantics work than one who accidently held onto one of these too long) but theoretically it is doable.