[英]Unknown behavior with shared_ptr
I have a sample code as below我有一个示例代码如下
#include <iostream>
#include <memory>
using namespace std;
class A {
public:
int n = 0;
};
class B {
public:
shared_ptr<A> ba;
};
class C {
public:
shared_ptr<A> ca;
shared_ptr<B> cb;
};
int main () {
cout << "Hello\n";
C c;
shared_ptr<A> a(new A);
c.ca = a;
c.cb->ba = a; // MAYBE PROBLEM HERE
return 0;
}
This code was compiled successfully, but when I run, it even doesn't print "Hello".这段代码编译成功,但是当我运行时,它甚至不打印“Hello”。 I'm newbie to C++ as well as smart pointer.
我是 C++ 和智能指针的新手。 Please help me explain the problem here.
请帮我解释这里的问题。 Thanks in advance!
提前致谢!
Possible fix for your code:您的代码的可能修复:
#include <iostream>
#include <memory>
using namespace std;
class A {
public:
int n = 0;
};
class B {
public:
shared_ptr<A> ba;
};
class C {
public:
C() {
cb = make_shared<B>();
}
shared_ptr<A> ca;
shared_ptr<B> cb;
};
int main () {
cout << "Hello\n";
C c;
shared_ptr<A> a = make_shared<A>();
c.ca = a;
c.cb->ba = a; // PROBLEM FIXED in constructor
return 0;
}
This is undefined behaviour.这是未定义的行为。 You never create an instance of B and on the line
c.cb->ba = a; // MAYBE PROBLEM HERE
您永远不会创建 B 的实例,并且在行
c.cb->ba = a; // MAYBE PROBLEM HERE
c.cb->ba = a; // MAYBE PROBLEM HERE
you are de-referencing a null pointer, which is UB. c.cb->ba = a; // MAYBE PROBLEM HERE
存在问题,您正在取消引用 null 指针,即 UB。
Note that shared pointers are default constructed to nullptr, not the default constructor of the owned type.请注意,共享指针默认构造为 nullptr,而不是拥有类型的默认构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.