简体   繁体   English

C ++:使用auto将类声明为函数内的变量

[英]C++: Using auto to declare classes as variables inside functions

I'm trying to use auto for all local variables inside my functions. 我正在尝试对函数中的所有局部变量使用auto。

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. 注意,定义test0完全可以,但是尝试执行与test1完全相同的声明类型是编译器错误。 Clearly is should be a compiler error, but in this case, does it mean obj can't be defined with auto? 显然应该是编译器错误,但是在这种情况下,这是否意味着无法使用auto定义obj I'm running into this problem with QT objects I don't have control over. 我遇到了我无法控制的QT对象的问题。

Am I suck still using the C++98 format for declaring variables or is there another way to use auto? 我是否仍在使用C ++ 98格式声明变量,还是有另一种使用auto的方法?

Thanks!!! 谢谢!!!

This is OK in C++17; 这在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. 有保证的复制省略会调整规则,以便在概念上甚至都不会调用move构造函数,因此删除还是无法访问都无关紧要。

Before then, if you love auto so much, you can do 在此之前,如果您热爱auto ,可以

auto&& test1 = obj();

This creates a temporary obj object and binds it to the reference test1 , extending its lifetime to that of the reference. 这将创建一个临时obj对象,并将其绑定到引用test1 ,将其生存期延长到该引用的生存期。 With a few exceptions, the behavior is pretty much identical to what you will get in C++17 with plain auto . 除了少数例外,其行为与使用普通auto在C ++ 17中获得的行为几乎相同。

In the declaration 在声明中

auto test1 = obj();

the compiler tries to move the object on the rhs, as it is a rvalue. 编译器尝试将对象移到rhs上,因为它是一个右值。 It cannot (as the move ctor is marked as deleted). 它不能(因为移动ctor被标记为已删除)。 Note that because the move ctor is deleted, then the copy ctor is deleted as well, although the compiler will only try to move (because the move ctor, even though deleted, it is still consider user-defined and it is selected as a candidate during overload resolution ). 请注意,因为删除了移动ctor,所以也会删除复制ctor,尽管编译器将仅尝试移动(因为即使删除了移动ctor,它仍被视为用户定义的, 因此被选择为候选对象。解决过载时 )。 Hence, your code doesn't compile. 因此,您的代码无法编译。

The error has nothing to do with the use of auto specifically. 该错误与专门使用auto无关。

obj test1 = obj();

doesn't compile as well. 也不编译。 obj() is a r-value, that the compiler tries to move but the move constructor is deleted. obj()是一个r值,编译器将尝试移动它,但move构造函数被删除。 Deleting the move constructor prevents the compiler of creating a copy constructor as well, so it can't copy it too, hence the error. 删除move构造函数也会阻止编译器创建复制构造函数,因此它也无法复制它,因此会出现错误。

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

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