c++ - std::shared_ptr 或 std::unique_ptr 赋值运算符重载

标签 c++ shared-ptr smart-pointers unique-ptr

我看不出为什么它们没有为它们模板化的类型的普通旧指针重载赋值运算符的原因。如果使智能指针接口(interface)尽可能接近普通旧指针的目标,那么他们为什么不像这样为赋值运算符重载?

inline std::shared_ptr<type> &operator=( const type * pointer)
{
    reset(a);
}

这样您就可以像使用普通指针一样使用它们,如下所示:

std::shared_ptr<int> test = new int;

这根本不是问题,只是想知道为什么他们要麻烦地重载几个运算符。

还想知道是否有一种方法可以重载全局赋值运算符来执行此操作,或者是否有任何理由我不应该这样做。

编辑:在此处添加对 Nawaz 关于他对代码格式的回答的回复。我只是写了这个测试程序,看看你说的对不对:

template<class T>
class peh
{
public:
    peh() {meh = 3;}
    const peh<T> & operator=(const int * peh)
    {
    }
};

void f( peh<int> teh)
{

}

int main()
{
    int * meh = new int;

    f(meh);

    system("PAUSE");
    return 0;
}

这里的错误是说没有来自 peh<int> 的可用转换至 int * .那么为什么 std::shared_ptr<int> 可以接受呢?至 int *

最佳答案

Also wondering if there's a way to overload the global assignment operator to do this, or if there's any reason i shouldn't.

没有。赋值运算符重载必须是一个成员函数。

顺便说一下,如果你想要以下功能,那么你不应该谈论赋值运算符,你应该问:为什么将原始指针作为参数的构造函数设为显式?为什么它不是隐式的?

//this code requires an implicit constructor, not assignment!
std::shared_ptr<int> test = new int;  //illegal 

这是非法的,但假设有一段时间这是允许的,那么您将能够调用以下函数并将原始指针作为参数传递:这样的功能将危险,因为其余答案解释(阅读评论):

void f(std::shared_ptr<int> test)
{
     //code

} //test will be destructed here  (when it goes out of scope)
  //if test.use_count() == 1, then the pointer which it manages 
  //will be destructed as well. (NOTE THIS POINT)

现在看危险部分:

int *ptr = new int;

f(ptr); 
//note that calling f is allowed if it is allowed:
//std::shared_ptr<int> test = new int;
//it is as if ptr is assigned to the parameter:
//std::shared_ptr<int> test = ptr;

//Question : now what happened in f()?
//Answer : inside f(), test (the shared_ptr) will infer that no one else
//refers to the pointer it contains, because test.use_count() == 1
//test is obviously wrong in this case, because it cannot prove that!

//DANGER
*ptr = 10; //undefined behavior, because ptr is deleted by the shared_ptr

请阅读评论。它解释了上面代码片段的每个部分。

关于c++ - std::shared_ptr 或 std::unique_ptr 赋值运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11283323/

相关文章:

c++ - 理解带有循环引用的 Shared_ptr?

object - 如何在UML中表示共享对象?

c++ - 为什么 shared_ptr<void> 合法,而 unique_ptr<void> 格式不正确?

c++ - STL vector 与列表 : Most efficient for graph adjacency lists?

c++ - NDRange 工作项数

c++ - '<function-style-cast >': cannot convert from ' initializer list' to 'std::shared_ptr<SDL_Window>' on creating shared_ptr with custom deleter

c++ - 如何优雅地使用智能指针在 C++ 中为复杂的生命周期建模?

c++ - 将 Vector<int> 转换为字符串

c++ - 复制省略可以在 synchronize-with 语句中发生吗?

C++设计题(需要便宜的智能指针)