Luke Dupin Luke Dupin - 8 months ago 56
C++ Question

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

I'm trying to use auto for all local variables inside my functions.

Take the following code:

class obj
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?



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();