Ai đó có thể giải thích lý do tại sao các sự cố sau trong main() khi phạm vi bên trong bị thoát? Tôi đang sử dụng Visual Studio 2013. Mặc dù tất cả mọi thứ là tốt với GCC 4.8.1, tôi nghi ngờ một cái gì đó là sai trong mã anyway. Tôi chỉ không nhận được nó.Tai nạn bí ẩn với shared_ptr
#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.
}
Thông báo lỗi tôi nhận được với VS2013 là:
thất bại khẳng định
_BLOCK_TYPE_IS_VALID (pHead-> nBlockUse)
Mã này khá nhỏ, tại sao không bước qua mã đó bằng trình gỡ lỗi? –
@CaptainObvlious có thực sự hữu ích không? –
@ n.m. Có lẽ không phải nhưng tôi là một masochist cho đến khi tôi đã có tô sáng của tôi của Fruity Pebbles. –