samedi 26 août 2017

Compilation error with unique_ptr

any idea why is this not compiling:

#include <iostream>
#include <vector>

class A {
public:
  A() : m_Member( 1 ) {
    std::cout << "Constructor called." << std::endl;
  }
  A( A const & t_a ) {
    m_Member = t_a.m_Member;
    std::cout << "Copy constructor called." << std::endl;
  }

  virtual ~A() {
    std::cout << "Destructor called." << std::endl;
    m_Member = 0;
  }
  void play() { std::cout << "Number is: " << m_Member << std::endl; }
private:
  int m_Member;
};

class B {
public:
  B() {
    std::cout << "Main object created!" << std::endl;
  }

  B( B & b ) {
    for( std::unique_ptr< A >& val: b.m_Array ) {
      m_Array.push_back( std::unique_ptr< A >( new A( *val ) ) );
    }
  }

  virtual ~B() {
    std::cout << "Main object destroyed!" << std::endl;
  }

  A& get( size_t const Index ) {
    return *m_Array[ Index ];
  }

  void add( A& a ) {
    m_Array.push_back( std::unique_ptr< A >( new A( a ) ) );
  }

private:
  std::vector< std::unique_ptr< A > > m_Array;
};

B createB() {
  B b;
  A a1;
  A a2;
  b.add( a1 );
  b.add( a2 );
  return b;
}

int main() {
  B b = createB();
  A& temp = b.get( 1 );
  temp.play();
  return 0;
}

I get this: error: no matching constructor for initialization of 'B' B b = createB();

Also, for this example, is there a better way to keep vector of objects? Note that I intentionally created objects in a function so that objects passed to class B will be deleted before B is destroyed. Reference wrapper did not work in this case because it was pointing to object that was already deleted. I tried to solve that by introducing unique_ptr, but then I got this error.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire