简体   繁体   English

如何避免转换运算符调用复制构造函数?

[英]How do I avoid a conversion operator to invoke the copy constructor?

As part of an optimization/cleanup pass, I'm trying to understand how to reduce temporary copies. 作为优化/清理过程的一部分,我试图了解如何减少临时副本。 While doing this I noticed that a conversion operator invoked my class's copy-constructor which otherwise can be avoided. 在执行此操作时,我注意到转换运算符调用了我的类的复制构造函数,否则可以避免。

struct CSetViewer
{
    int s;
    CSetViewer(int size) : s(size) {}
    CSetViewer(const CSetViewer &) = delete;
    CSetViewer &operator=(const CSetViewer &) = delete;
    CSetViewer(CSetViewer &&) = delete;
    CSetViewer &operator=(CSetViewer &&) = delete;

};

struct CSet
{
    operator CSetViewer() { return {1}; }
    CSetViewer GetSetViewer() { return {1}; }
};

void testSet(const CSetViewer &set) {}

void main()
{
    CSet set;
    testSet(set.GetSetViewer());
    testSet(set); // Error: attempting to reference a deleted function
}

In the following code, the first call to testSet compiles fine, but the second seems to want to invoke the copy constructor. 在下面的代码中,第一次调用testSet编译正常,但第二次调用似乎想要调用复制构造函数。

Adding: 添加:

void testSet(CSetViewer &&set) {}

Makes the code compile (VS 2017), but I really don't understand why as I thought that const-reference version would suffice in this situation. 使代码编译(VS 2017),但我真的不明白为什么我认为const-reference版本就足以满足这种情况。

How is the conversion operator different from the GetSetViewer function? 转换运算符与GetSetViewer函数有何不同? Can I make the code above work with the conversion operator without invoking the copy or move constructor? 我可以使用转换运算符使上面的代码无需调用副本或移动构造函数吗?

This is a known bug of Microsoft Visual Studio . 这是Microsoft Visual Studio的已知错误 A bug report has been filed the 2018-11-12. 已提交错误报告2018-11-12。 No news from there. 没有消息。

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

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