jeudi 29 novembre 2018

Is there some sort of copy destructor tech?

For example I got a class like this:

#include <iostream>
#include <functional>

class TestClass {
 public:
  explicit TestClass(std::function<void(void)> f) : f_(std::move(f)) {}
  TestClass(const TestClass &) = delete;
  TestClass(TestClass &&testobj) {
    f_ = testobj.f_;
    testobj.f_ = default_f_;
  }
  ~TestClass() { f_(); }
 private:
  static std::function<void(void)> default_f_;
  std::function<void(void)> f_;
};

std::function<void(void)> TestClass::default_f_ = [] { std::cout << "do nothing\n"; };

int main() {
  std::function<void(void)> f = [] { std::cout << "do something\n"; };
  TestClass t1(f);
  TestClass t2(std::move(t1));
}

Even if the old class is useless, The destructor has to be called and in this case, a useless function which duty is only to make sure the f_ is point to something, this is not very efficiency.

So is there some sort of copy destructor tech to avoid this?

Aucun commentaire:

Enregistrer un commentaire