简体   繁体   English

解引用共享指针并分配给它

[英]Dereferencing a shared pointer and assigning to it

Is it ok to dereference a shared pointer, assign and assign a new object to it like so: 可以取消对共享指针的引用,为它分配并分配一个新对象,这样可以吗:

void foo()
{
    std::shared_ptr<std::string> x =
            std::make_shared<std::string>();

    bar(*x); // is this fine?
    // x == bsl::string("WHATEVER")
}

void bar(string& y)
{
    y = string("whatever");
}

Yes, this is valid. 是的,这是有效的。 Operator * returns the result of dereferencing the stored (raw) pointer. 运算符*返回解引用已存储(原始)指针的结果。

Dereferencing a (raw) pointer does not make a copy or return a temporary: dereferencing a pointer when passing by reference 取消引用(原始)指针不会产生副本或返回临时值: 通过引用传递时取消引用指针

It is fine to do it but I would use the shared_ptr::get() operator in order to be more obvious regarding the fact that we are not using a raw pointer. 这样做很好,但是我将使用shared_ptr::get()运算符,以便对我们不使用原始指针的事实更加清楚。

void foo()
{
    std::shared_ptr<std::string> sharedPtr = std::make_shared<std::string>();
    bar(*sharedPtr.get());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM