0

In the following piece of code, I'm retrieving a shared_ptr<A> from a function. I then dynamically cast the pointer to a deriving class and store it in a shared_ptr<B>. The original pointer is not a nullptr.

shared_ptr<B> storage = nullptr;

if (...)
{
  shared_ptr<A> definition = getSharedPointer();

  // Store the lambda
  storage = dynamic_pointer_cast<B>(definition);
}

I would expect the dynamic_pointer_cast and storage to storage to increase the total reference count to 2. Then, when I leave the scope of the if-statement, storage's reference count should be one.

Yet, when I tried to call a method on storage, I get a EXC_BAD_ACCESS, implying I'm reading in a deleted pointer.

storage->foo(...)->bar(...);

Is my logic wrong? Is this a bug in clang (can't imagine)?

EDIT

I seem to have found the error, which has nothing to do with the pointers. The function bar() actually gave the problem. If anyone ever reads this: the above code is perfectly valid.

4

1 回答 1

3

这个例子工作正常:

#include <memory>

using namespace std;

struct A {
    virtual ~A() {}
};
struct B : A {};

shared_ptr<A> getSharedPointer() {
    return make_shared<B>();
}

#include <iostream>

int main() {
    shared_ptr<B> storage = nullptr;

    if (true)
    {
      shared_ptr<A> definition = getSharedPointer();

      // Store the lambda
      storage = dynamic_pointer_cast<B>(definition);
    }

    cout << storage.get() << endl;
}

看起来你shared_ptr<A>的不是指向 aB并且结果是dynamic_pointer_castis nullptr。也许调试语句会有所帮助:

if (...)
{
  shared_ptr<A> definition = getSharedPointer();
  cerr << "as A: " << definition.get()
       << ", as B: " << dynamic_cast<B>(definition.get()) << endl;

  // Store the lambda
  storage = dynamic_pointer_cast<B>(definition);
}
于 2013-08-01T15:17:52.800 回答