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

Author Topic: NonCopyable class member?  (Read 983 times)

0 Members and 1 Guest are viewing this topic.

Millsialix

  • Guest
NonCopyable class member?
« on: March 08, 2019, 10:46:12 pm »
Hi,
Everything is in the title, I want to create a vector with some classes with NonCopyable members (sf::Shader, but the error is the same with other classes), and my compiler says that I use a deleted function, and I'm almost sure that is because my class member is a NonCopyable:

#include <SFML/Graphics.hpp>

class Object {

        public:
                Object(){};

        protected:
                sf::Shader m_shader;
};

int main(){
    std::vector<Object> tmp( 27, Object());
}
 

Error:
Code: [Select]
G:\...\MinGW-5.1.0\...\stl_construct.h|75|error: use of deleted function 'Object::Object(const Object&)'|
G:\...\main.cpp|3|note: 'Object::Object(const Object&)' is implicitly deleted because the default definition would be ill-formed:|
G:\...\SFML-2.5.0\...\NonCopyable.hpp|77|error: 'sf::NonCopyable::NonCopyable(const sf::NonCopyable&)' is private|

I don't really want to use pointers or std::shared_ptr to use SFML things, so here is my question: Am I doing something wrong, or is it just the way SFML works?

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 10801
    • View Profile
    • development blog
    • Email
Re: NonCopyable class member?
« Reply #1 on: March 09, 2019, 12:15:47 am »
A std::vector requires your class to be copyable and since you didn't restrict the constructor generation, your Object class gets a default copy-constructor, except the Object class can't be copied, because it holds non-copyable resources.

Probably better to manage your resources externally, with something like a resource holder and pass a reference around.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6286
  • Thor Developer
    • View Profile
    • Bromeon
Re: NonCopyable class member?
« Reply #2 on: March 10, 2019, 02:00:24 pm »
Since C++11, std::vector only requires copyable elements for some operations (such as copying/assigning the vector). Otherwise, it supports movable elements -- however SFML classes are not move-enabled (since they're written in C++03, and when explicitly specifying other constructors, no move constructor/assignment operator is generated).

If you're interested, one possible solution is my Thor library which manages resources for you. You load resources such as sf::Shader in one central place, and distribute shared pointers to them. Here is the link to the tutorial.
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

 

anything