C++ 为什么make_shared在不同的呼叫中分配相同的地址?
为什么这会使_shared在两个单独的调用中分配相同的内存地址C++ 为什么make_shared在不同的呼叫中分配相同的地址?,c++,c++11,C++,C++11,为什么这会使_shared在两个单独的调用中分配相同的内存地址 typedef struct { int a; int b; int c; } test_t; void call_func() { std::shared_ptr<test_t> tst = std::make_shared<test_t>(); std::cout << "addr: " << tst << std::endl
typedef struct {
int a;
int b;
int c;
} test_t;
void call_func()
{
std::shared_ptr<test_t> tst = std::make_shared<test_t>();
std::cout << "addr: " << tst << std::endl;
}
int main()
{
call_func();
call_func();
}
typedef结构{
INTA;
int b;
INTC;
}测试;
void call_func()
{
std::shared_uptr tst=std::make_ushared();
std::cout因为它可以。
call_func()
在可用内存中创建一个新的test_t
对象,并将其包装在std::shared_ptr
中。退出call_func()
时,如果std::shared_ptr
超出范围,则test_t
对象将被销毁
因此,当第一次调用call_func()
退出时,它使用的内存已被释放,并且在第二次调用call_func()
时可以重新使用
这是正常的行为,不需要担心。很可能您不知道变量的范围!新的侏儒会这样声明!