PassByVal、PassByRef 和 PassByConstRef 的比较 std::shared_ptr (什么

Comparison of PassByVal, PassByRef, and PassByConstRef of std::shared_ptr (What can(cannot) be changed)

本文关键字:shared ptr 什么 std 比较 PassByRef PassByConstRef PassByVal      更新时间:2023-10-16
#include <iostream>
#include <string>
#include <memory>
std::shared_ptr<std::string> ptrStr(new std::string("One"));
// increases the reference count to std::string("One") by one after entering the function
// decreases the reference count to std::string("One") by one before exiting the function
void PassByValue(std::shared_ptr<std::string> msg)
{
    msg->clear();                              // clears the string pointed by ptrStr
    msg.reset(new std::string("hello world")); // doesn't change the value of ptrStr
                                               // because it only changes a local copy of ptrStr
                                               // which will be destroyed when the function is returned.
                                               // Note the msg, the local copy of ptrStr, points to the same
                                               // resource where ptrStr points to.
}
// doesn't affect the reference count
void PassByReference(std::shared_ptr<std::string> &msg)
{
    msg->clear();                              // clears the string pointed by ptrStr
    msg.reset(new std::string("hello world")); // does change the value of ptrStr
}
// doesn't affect the reference count
void PassByConstReference(const std::shared_ptr<std::string>& msg)
{
    msg->clear();                              // clears the string pointed by ptrStr
    msg.reset(new std::string("hello world")); // compilation errors
}
int main(int argc, char* argv[])
{
    // Each time only one of the following three lines is executed
    //PassByValue(ptrStr);
    //PassByReference(ptrStr);
    //PassByConstReference(ptrStr)
    std::cout << *ptrStr << std::endl;
    return 0;
}

注意:我不是在争论哪种传递机制是好是坏。我只想了解std::shared_ptr传递机制不同的后果,只想关注传递std::shared_ptr作为函数参数。

问题1>如果我错了,请帮助阅读评论并纠正我

问题2>是不是真的,不管选择哪种机制,总能改变std::shared_ptr所指的资源?

问题 3> std::shared_ptr 是否与其他函数参数相似,并且在 PassByValue、PassByReference 和 PassByConstReference 方面具有类似的行为。

谢谢

问题1>如果我错了,请帮助阅读评论并纠正我

根据我的理解,你的评论是正确的。

问题2> 不管选择哪种机制,你总是可以改变std::shared_ptr所指向的资源,这是真的吗?

嗯,有点。您始终可以从std::shared_pointer中检索原始指针。当您将其作为const传递时,您将获得一个const原始指针。如果要操作指向对象的内容,则会出现编译错误。但是有一些方法可以将const指针转换为普通指针,例如使用 const_cast .

问题 3>std::shared_ptr 与其他函数参数相似,并且在 PassByValue、PassByReference 和 PassByConstReference 方面具有类似的行为,这是真的吗?

从C++的角度来看,std::shared_pointer s只是与其他任何类型一样的类型,所以不,关于参数传递的方法,这里没有区别。

  1. 您的所有评论都是完全正确的。
  2. 你可以路过std::shared_ptr<std::string const>.在这种情况下,shared_ptr指向的资源是不可更改的。
  3. 我不确定你在问什么,但是通过参数的规则没有std::shared_ptr的特殊情况.