반응형
This code does not compile, but i couldnot find what is wrong with the code. I think shared_ptr matters.

#include <memory>
#include <iostream>
using namespace std;

class A {
public:
  virtual const void test() const = 0;
  ~A() {  }
};
class AImpl : public A {
public:
  const void test() const {
    std::cout << "AImpl.test" << std::endl;
  }
};
class B {
public:
  B() {  }
  ~B() { 
  }

  shared_ptr<A> CreateA() {
    a_ = make_shared<AImpl>(new AImpl());
    return a_;
  }
private:
  shared_ptr<A> a_;
};

int main() {

  B *b = new B();
  shared_ptr<A> p = b->CreateA();
  if (b) {
    delete b;
    b = NULL;
  }
}

 

 

ou are using make_shared incorrectly. You dont need to use new in make_shared, it defeats the whole purpose of this function template.

This function is typically used to replace the construction std::shared_ptr(new T(args...)) of a shared pointer from the raw pointer returned by a call to new. In contrast to that expression, std::make_shared typically allocates memory for the T object and for the std::shared_ptr's control block with a single memory allocation (this is a non-binding requirement in the Standard), where std::shared_ptr(new T(args...)) performs at least two memory allocations.

a_ = make_shared<AImpl>(); // correct
//a_ = make_shared<AImpl>(new AImpl()); // not correct

 

 

ref : https://stackoverflow.com/questions/39651748/whats-wrong-with-the-code-using-shared-ptr-with-pure-virtual-base-class

반응형

+ Recent posts