我正在尝试对我的函数中的所有局部变量使用auto。
请使用以下代码:
class obj { public: obj() {}; obj( obj&& o ) = delete; }; int main() { obj test0; auto test1 = obj(); return 0; }编译代码:
$ g++ --std=c++1z main.cpp main.cpp: In function ‘int main()’: main.cpp:13:20: error: use of deleted function ‘obj::obj(obj&&)’ auto test1 = obj();请注意,定义test0是完全可以的,但尝试执行完全相同类型的test1声明是编译器错误。 显然应该是编译器错误,但在这种情况下,是否意味着obj无法用auto定义? 我正在使用我无法控制的QT对象来解决这个问题。
我还在使用C ++ 98格式来声明变量,还是有其他方法可以使用auto?
谢谢!!!
I'm trying to use auto for all local variables inside my functions.
Take the following code:
class obj { public: obj() {}; obj( obj&& o ) = delete; }; int main() { obj test0; auto test1 = obj(); return 0; }Compiling the code:
$ g++ --std=c++1z main.cpp main.cpp: In function ‘int main()’: main.cpp:13:20: error: use of deleted function ‘obj::obj(obj&&)’ auto test1 = obj();Notice that defining test0 is completely okay, but attempting to do the exact same type of declaration of test1 is a compiler error. Clearly is should be a compiler error, but in this case, does it mean obj can't be defined with auto? I'm running into this problem with QT objects I don't have control over.
Am I suck still using the C++98 format for declaring variables or is there another way to use auto?
Thanks!!!
最满意答案
这在C ++ 17中是可以的; 保证复制省略调整规则,以便移动构造函数甚至不在概念上调用,因此删除或无法访问它并不重要。
在此之前,如果你非常喜欢auto ,你可以做到
auto&& test1 = obj();这将创建一个临时obj对象并将其绑定到引用test1 ,从而将其生命周期延长到引用的生命周期。 除了少数例外,该行为与使用普通auto C ++ 17中的行为非常相似。
This is OK in C++17; guaranteed copy elision adjusts the rules so that a move constructor isn't even conceptually called, so it doesn't matter if it's deleted or inaccessible.
Before then, if you love auto so much, you can do
auto&& test1 = obj();This creates a temporary obj object and binds it to the reference test1, extending its lifetime to that of the reference. With a few exceptions, the behavior is pretty much identical to what you will get in C++17 with plain auto.
更多推荐
发布评论