智能指针与哑指针:多态行为奇怪

use*_*343 3 c++ polymorphism pointers smart-pointers c++11

我在一些更大的代码中调试了一个问题,并且发现了一些关于智能指针及其多态属性的奇怪之处.通过简单的示例可以很好地看到这一点:

#include <iostream>
#include <memory>

using namespace std;

class A {
public:
  virtual void who() {cout << "I am class A" << endl; };
}; 

class B : public A{
public:
  void who() {cout << "I am class B" << endl; };
}; 

int main(int argc, char *argv[])
{
  B b;  
  A * aptr = &b;
  aptr->who(); //Output: I am class B

  B * bptr = &b;
  bptr->who(); //Output: I am class B

  shared_ptr<A> sptr;
  sptr = make_shared<A>(b);
  sptr->who(); //Output: I am class A

  sptr = make_shared<B>(b);
  sptr->who(); //Output: I am class B

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

前两个输出对我来说很有意义,但是当我初始化的唯一对象是B类时,为什么我可以访问A中定义的成员函数(参见第三个输出)?从某种意义上说,这是一个很好的技巧,可以访问派生类型对象的基类成员.不过,这对我来说仍然有点怪异......

任何人都可以解释为什么这种行为可以使用智能指针而不是常规指针?

asc*_*ler 11

std::make_shared总是创造一个全新的对象.那是,

sptr = make_shared<A>(b);
Run Code Online (Sandbox Code Playgroud)

更像是

A* p1 = new A(b);
Run Code Online (Sandbox Code Playgroud)

而不是喜欢

A* p2 = &b;
Run Code Online (Sandbox Code Playgroud)

p1并且返回值make_shared根本没有指向b.