Fat*_*sis 1 c++ smart-pointers shared-ptr unique-ptr
我没有看到为什么这些没有为它们被模板化的类型的普通旧指针赋值操作符重载的原因.如果使智能指针的接口尽可能接近普通的旧指针,那么为什么它们不像这样对赋值运算符进行重载?
inline std::shared_ptr<type> &operator=( const type * pointer)
{
reset(a);
}
Run Code Online (Sandbox Code Playgroud)
这样你可以像使用普通指针一样使用它们,如下所示:
std::shared_ptr<int> test = new int;
Run Code Online (Sandbox Code Playgroud)
它根本不是一个问题,只是想知道为什么他们遇到了只是让一些运营商超载的麻烦.
还想知道是否有一种方法来重载全局赋值运算符来执行此操作,或者是否有任何原因我不应该这样做.
编辑:在此处为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;
}
Run Code Online (Sandbox Code Playgroud)
这个错误在这里说出来也从没有可用的转换peh<int>来int *.那么,为什么它可以接受std::shared_ptr<int>到int *?
还想知道是否有一种方法来重载全局赋值运算符来执行此操作,或者是否有任何原因我不应该这样做.
否.赋值运算符重载必须是成员函数.
顺便说一句,如果你想要以下功能,那么你不应该谈论赋值运算符,你应该问:为什么构造函数将原始指针作为参数explicit?为什么不隐含?
//this code requires an implicit constructor, not assignment!
std::shared_ptr<int> test = new int; //illegal
Run Code Online (Sandbox Code Playgroud)
这是非法的,但假设有一段时间允许这样做,那么你就可以调用以下函数传递一个原始指针作为参数:这样的功能会很危险,因为其余的答案解释了(阅读评论) :
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)
Run Code Online (Sandbox Code Playgroud)
现在看危险的部分:
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
Run Code Online (Sandbox Code Playgroud)
请阅读评论.它解释了上面代码片段的每个部分.