boost-ext / di

C++14 Dependency Injection Library
https://boost-ext.github.io/di
1.13k stars 137 forks source link

Why is copy constructor called when using injector? #472

Open Gomox11 opened 4 years ago

Gomox11 commented 4 years ago

Hello everyone!

Here is my example of creating an object of type SomeClass:

#include <mutex>
#include <string>

#include <di.hpp>

struct DataStruct {
  std::string some_string_;
  std::mutex some_mutex_;
};

class SomeClass {
 public:
  SomeClass(DataStruct& data_struct) : data_struct_{data_struct} {
  }

 private:
  DataStruct& data_struct_;
};

int main() {
  auto injector = boost::di::make_injector();
  auto some_class = injector.create<std::unique_ptr<SomeClass>>();
}

This causes this compilation error because std::mutex is obviously not copyable: error: use of deleted function ‘std::mutex::mutex(const std::mutex&)

If I wasn't using Boost.DI I could simply use make_unique without worrying about any copy or move operations:

struct DataStruct data_struct{};
auto some_class = std::make_unique<SomeClass>(data_struct);

However, using Boost.DI, the only workaround I've found is defining the struct's move constructor:

struct DataStruct {
  std::string some_string_;
  std::mutex some_mutex_;

  DataStruct() = default;

  DataStruct(DataStruct&&) {
  }
};

How do you guys handle situations like this? Am I missing something? Thanks in advance :)

vpatov commented 2 years ago

I am also experiencing a very similar issue, I have a class that I initialized using Boost.DI, that also has a std::mutex member.

vpatov commented 2 years ago

Your workaround didn't work for me, so I worked around it by using a smart pointer for the std::mutex variable instead. Probably not ideal, but worked for me.

charles-huet-ixxi commented 2 years ago

I am evaluating boost.DI and am running in the exact same issue, any details on why this is necessary ?

Funny thing being types that are non-copyable can be created by the injector to give to the created class.