You are not logged in.

#1 2024-04-21 06:33:09

Baird
Member
Registered: 2023-03-10
Posts: 16

clang-tidy union warning

I'm trying to write some SFML code, but I got this warning message about union:
Do not access members of unions; use (boost::)variant instead [cppcoreguidelines-pro-type-union-access]

code:

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>

int main()
{
    const sf::VideoMode video{800, 600};
    sf::RenderWindow window{video, "Window"};

    while (window.isOpen()) {
        sf::Event event{};
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            }
            if (event.type == sf::Event::Resized) {
                sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height); // HERE I GOT THE WARNING MESSAGE
                window.setView(sf::View(visibleArea));
            }
        }

        const sf::Vector2f rect_pos{320.0F, 240.0F};
        const sf::Vector2f rect_size{128.0F, 128.0F};
        sf::RectangleShape rectangle{rect_size};
        rectangle.setFillColor(sf::Color::Red);
        rectangle.setPosition(rect_size);

        window.clear(sf::Color::Green);
        window.draw(rectangle);
        window.display();
    }
}

Is disabling this warning the only solution?
Or I can do something to wrap my code?

Last edited by Baird (2024-04-21 06:34:53)

Offline

#2 2024-04-21 06:55:31

schard
Forum Moderator
From: Hannover
Registered: 2016-05-06
Posts: 2,116
Website

Re: clang-tidy union warning

Reading a member of a union that has not most recently be written is UB. Don't do that.


Inofficial first vice president of the Rust Evangelism Strike Force

Offline

#3 2024-04-21 07:02:48

Baird
Member
Registered: 2023-03-10
Posts: 16

Re: clang-tidy union warning

schard wrote:

Reading a member of a union that has not most recently be written is UB. Don't do that.

I think checking sf::Event::Resized should be safe for access

When I write my own code, I don't use union.
But I don't know how to avoid warnings in a good way when there are unions in the library.

Offline

Board footer

Powered by FluxBB