【发布时间】:2014-09-20 23:27:11
【问题描述】:
有人可以解释为什么退出内部范围时 main() 中的以下崩溃?我正在使用 Visual Studio 2013。虽然 GCC 4.8.1 一切都很好,但我怀疑代码中有问题。我就是不明白。
#include <iostream>
#include <memory>
class Person; class PersonProxy;
class PersonInterface {
public:
virtual ~PersonInterface() = default;
virtual PersonProxy* getProxy() const = 0;
virtual void createProxy (Person*) = 0;
};
class Person : public PersonInterface {
private:
std::string name;
std::shared_ptr<PersonProxy> proxy;
public:
Person() = default;
explicit Person (const std::string& n) : name(n) {}
public:
virtual PersonProxy* getProxy() const override {return proxy.get();}
inline void createProxy (Person* p);
};
class PersonProxy : public PersonInterface {
private:
std::shared_ptr<Person> actual;
public:
explicit PersonProxy (Person* p) : actual (std::shared_ptr<Person>(p)) {}
explicit PersonProxy (std::shared_ptr<Person> p) : actual (p) {}
void rebind (std::shared_ptr<Person> p) {actual = p;}
virtual PersonProxy* getProxy() const override {return actual->getProxy();}
virtual void createProxy (Person* p) override {actual->createProxy(p);}
};
class Girl : public Person {
public:
Girl (const std::string& name) : Person (name) {createProxy (this);}
};
inline void Person::createProxy (Person* p) {
proxy = std::shared_ptr<PersonProxy>(new PersonProxy(p));
}
int main() {
{
Girl* a = new Girl("a");
// std::shared_ptr<Girl> a = std::make_shared<Girl>("a"); // Using this crashes with Visual Studio 2013 on the line 'a->getProxy()->rebind(b);'
std::shared_ptr<Girl> b = std::make_shared<Girl>("b");
a->getProxy()->rebind(b);
std::cout << "rebind succeeded." << std::endl;
}
std::cout << "Exited scope." << std::endl; // Exiting scope crashes with VS 2013.
}
我用 VS2013 得到的错误信息是:
断言失败
_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
【问题讨论】:
-
代码很小,为什么不用调试器单步调试呢?
-
@CaptainObvlious 真的有用吗?
-
@n.m.可能不会,但我是一个受虐狂,直到我早上吃了一碗果味鹅卵石。
-
在同一个作用域内声明两个同名变量合法吗?
-
@Ginger。我现在解决了混乱,尽管它与问题无关。这是实际合法的。
标签: c++ shared-ptr