C ++:使用auto将类声明为函数内的变量(C++: Using auto to declare classes as variables inside functions)

编程入门 行业动态 更新时间:2024-10-26 12:24:23
C ++:使用auto将类声明为函数内的变量(C++: Using auto to declare classes as variables inside functions)

我正在尝试对我的函数中的所有局部变量使用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.

更多推荐

本文发布于:2023-07-22 12:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   函数   声明   auto   functions

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!