[英]passing std::shared_ptr<<std::vector<double>> to a function
I am trying to understand the use of shared_ptrs. 我试图了解shared_ptrs的用法。 The simple code below
下面的简单代码
#include<iostream>
#include<vector>
#include<memory>
void funct(std::shared_ptr<std::vector<double>> H){
H->push_back(1.00);
}
int main()
{
std::shared_ptr<std::vector<double>> H;
funct(H);
return 0;
}
gives me a segmentation fault which I can't seem to understand. 给了我似乎无法理解的细分错误。 What am I doing wrong here?
我在这里做错了什么?
H
is initialized with a null pointer, so dereferencing it causes undefined behaviour. H
使用空指针初始化,因此对其取消引用会导致未定义的行为。
You perhaps meant to do this: 您也许打算这样做:
auto H = std::make_shared<std::vector<double>>();
This would create a new empty std::vector<double>
object owned by H
. 这将创建一个
H
拥有的新的空std::vector<double>
对象。 A pointer to an empty vector is quite different from a null pointer (which points to no vector at all). 指向空向量的指针与空指针(完全不指向向量)有很大的不同。
Your smart pointer H
is default created . 您的智能指针
H
是默认创建的 。 When a smart pointer is default created, its pointer value is a nullptr
. 默认创建智能指针时,其指针值为
nullptr
。
So when you dereference it ( *H
or H->
), you will cause Undefined Behaviour . 因此,当您取消引用(
*H
或H->
)时,将导致未定义行为 。
In order to create a valid shared pointer, you can use the std::make_shared()
function. 为了创建有效的共享指针,可以使用
std::make_shared()
函数。
For example: 例如:
int main() {
auto H = std::make_shared<std::vector<double>>();
// Now H is not a nullptr pointer.
funct(H);
return 0;
}
(OT) Simple Advise Passing a shared_ptr
by reference is probably not a good idea! (OT) 简单建议通过引用传递
shared_ptr
可能不是一个好主意!
A shared pointer (or any smart pointer) behaves like a regular pointer in the sense that it is initially a nullptr, and after initialization will it start pointing at a specific memory address. 共享指针(或任何智能指针)在某种意义上类似于常规指针,在某种意义上它最初是一个nullptr,并且在初始化之后它将开始指向特定的内存地址。 In the case of a shared_ptr the initalization is best done with the make_shared function, which is described nicely in the reference if you need it.
对于shared_ptr,最好使用make_shared函数完成初始化,如果需要,可以在参考中对它进行很好的描述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.