Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: create a window from another method and returning it?  (Read 2532 times)

0 Members and 1 Guest are viewing this topic.

st3ph4n

  • Newbie
  • *
  • Posts: 1
    • View Profile
create a window from another method and returning it?
« on: February 26, 2022, 07:18:25 am »
i basically have a struct in other file that i have included, and inside its a method to

struct sfml {
        sf::RenderWindow& init_window() {
                globals.window.settings.antialiasingLevel = 8;
                sf::RenderWindow window = sf::RenderWindow(sf::VideoMode(sf::VideoMode::getDesktopMode().width, sf::VideoMode::getDesktopMode().height), globals.window.title, sf::Style::None, globals.window.settings);
                return window;
        }
} sfml;

but this doesnt work. the following error pops up in this file:
error C2280: 'sf::RenderWindow::RenderWindow(const sf::RenderWindow &)': attempting to reference a deleted function

in the main.cpp file:

sf::RenderWindow& window = sfml.init_window();

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
Re: create a window from another method and returning it?
« Reply #1 on: February 28, 2022, 10:50:24 am »
If you search the internet for "attempting to reference a deleted function" you'll quickly learn, that this means you're trying to use a deleted copy constructor, which in turn means that you're trying to copy a RenderWindow, which is explicitly prohibited, because copying a window doesn't "physically" make sense (you can't have a copy of a window).

You constructor a window locally in the init_window and return a reference to it, but the local variable ceases to exist as soon as you leave the function, thus the reference is also invalid.
If you're using C++17, you could return by-value and depend on guaranteed RVO / copy elision.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

 

anything