使用 shared_ptr 和纯虚拟基础 class 的代码有什么问题

what's wrong with the code using shared_ptr with pure virtual base class

这段代码无法编译,但我找不到代码有什么问题。我认为 shared_ptr 很重要。

#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;
  }
}

您使用的 make_shared 不正确。你不需要在 make_shared 中使用 new,它违背了这个函数模板的全部目的。

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