0
votes

Getting error in use of auto for the implicit conversion.

Capturing the return of v.size() using int variable is ok but auto complains. Compiler error does inform it is because of narrowing conversion .But I would like to understand in terms memory how this happens and why auto is not allowing it do that whereas normal conversion is ok

#include <iostream>
#include <vector>
int main()
{
    auto v = std::vector<int>{ 1, 2, 3 };

    auto  c = 'h';
    auto n2 = int{c};
    std::cout<<n2<<" "<<c;

    auto size = int{v.size()};
    std::cout<<size;

    int size_1 = v.size();
    std::cout<<size_1;

}

Error because of below line auto size = int{v.size()};

main.cpp: In function 'int main()': main.cpp:11:27: error: narrowing conversion of 'v.std::vector::size()' from 'std::vector::size_type {aka long unsigned int}' to 'int' inside { } [-Wnarrowing]

When that line is commented it works perfectly

#include <iostream>
#include <vector>
int main()
{
    auto v = std::vector<int>{ 1, 2, 3 };

    auto  c = 'h';
    auto n2 = int{c};
    std::cout<<n2<<" "<<c;

    //auto size = int{v.size()};
    //std::cout<<size;

    int size_1 = v.size();
    std::cout<<size_1;

}

Output

104 h3

DEMO LINK

1
What's so hard to understand? You are converting a long unsigned int to int - which may truncate it. That's bad and you should be glad your friendly compiler warns you about it. - Jesper Juhl
"Capturing the return of v.size() using int variable is ok" - No, it is not. size() does not return int. There is conversion happening and the result may not be what you expect. Braced initialization (and the compiler warning) is saving you from making a mistake here. - Jesper Juhl

1 Answers

5
votes

This has nothing to do with auto. You will get the same warning if you use

int size = int{v.size()};

The issue here is int{v.size()} is using braced initialization to initialize a temporary int. A narrowing conversion in braced initialization is what causes the diagnostic to be displayed.


Do note that

int size_1 = v.size();

Is also a narrowing conversion, it is just not one where the standard mandates that a warning/error be emitted.