giGii

class with unique ptr fields

May 10th, 2023
731
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <vector>
  2. #include <memory>
  3. #include <string>
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. struct A {
  9.     virtual ~A() = default;
  10.     A(int ba, string ca, string ga = "abcdefg"s)
  11.     : b(ba)
  12.     , c(ca)
  13.     , g(ga)
  14.     {
  15.     }
  16.  
  17.     int b;
  18.     string c;
  19.     string g;
  20. };
  21.  
  22. struct D : public A {
  23.     D(int ba, string ca, bool ed, char fd)
  24.     : A(ba, ca)
  25.     , e(ed)
  26.     , f(fd)
  27.     {
  28.     }
  29.  
  30.     bool e;
  31.     char f;
  32. };
  33.  
  34. class B {
  35. public:
  36.     void Push(A* raw_data) {
  37.         data_.emplace_back(raw_data);
  38.     }
  39.     const vector<unique_ptr<A>>& Get() const {
  40.         return data_;
  41.     }
  42. private:
  43.     vector<unique_ptr<A>> data_;
  44. };
  45.  
  46. class X {
  47. public:
  48.     X(const B& b) : b_(b) {}
  49.     ~X() = default;
  50. private:
  51.     B b_; // static assertion failed: result type must be constructible from input type
  52.     // const B& b_; // надо так
  53. };
  54.  
  55. int main() {
  56.     B b;
  57.  
  58.     A* a1 = new A(3, "three"s);
  59.     A* d1 = new D(0, "zero"s, true, 'a');
  60.  
  61.     b.Push(a1);
  62.     b.Push(d1);
  63.  
  64.     X compose_b(b); // static assertion failed: result type must be constructible from input type
  65.     // потому что X хранит B b по значению; сам B имеет поле с unique_ptr, поэтому экземпляры B
  66.     // некопируемые, а хранение по значению в X предполагает создание копии B, что невозможно
  67. }
Advertisement
Add Comment
Please, Sign In to add comment