【发布时间】:2019-01-14 00:20:44
【问题描述】:
我正在使用一个表达式模板类,它不应该被实例化以避免悬空引用。但我很想用 auto 声明一个变量,然后“auto”创建一个临时类的命名实例。
如何在以下代码中禁用临时类的自动声明?
class Base
{
};
class Temp : public Base
{
public:
Temp() {}
Temp(int, int) {}
Temp(const Temp&) = default;
Temp(Temp&&) = default;
};
Temp testFunc(int a, int b) {
return Temp{a,b};
}
int main() {
Base a = testFunc(1,2); // this should work
auto b = testFunc(1,2); // this should fail to compile
return 0;
}
【问题讨论】:
-
Nitpick:
Temp(const Test&)和Temp(Test&&)应该是Temp(const Temp&)和Temp(Temp&&)。 -
你也要禁止
Temp a = testFunc(1,2);吗? -
Temp a = testFunc(1,2) 应该可以工作,而 auto b = testFunc(1,2) 不应该
-
这是不可能的。
标签: c++14 c++17 auto copy-elision deleted-functions