[英]Can I assign 0 to a shared_ptr? Why?
I realized the following compiles fine in GCC 4.7: 我意识到以下编译在GCC 4.7中很好:
#include <memory>
int main() {
std::shared_ptr<int> p;
p = 0;
}
However, there is no assignment operator from int
or from int*
, and there is no implicit constructor from either int
or int*
either. 但是,从没有赋值运算符int
或int*
,并且有来自要么没有隐式构造函数int
或int*
无论是。 There is a constructor from int*
, but that one is explicit. int*
有一个构造函数,但是那个是明确的。 I checked the standard library implementation and the constructor is indeed explicit, and no fishy assignment operators are in sight. 我检查了标准库实现,构造函数确实是显式的,并且看不到任何可疑的赋值运算符。
Is the program actually well-formed or is GCC messing with me? 该计划实际上是否格式正确或海湾合作委员会与我搞混?
The reason this works is this short quote from the standard: 这有效的原因是标准的这个简短引用:
§4.10 [conv.ptr] p1
A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type
std::nullptr_t
. 空指针常量是整数类型的整数常量表达式 (5.19)prvalue, 其计算结果为零或类型为std::nullptr_t
。 [...] A null pointer constant of integral type can be converted to a prvalue of typestd::nullptr_t
. [...]整数类型的空指针常量可以转换为std::nullptr_t
类型的prvalue。 [...] [...]
And the fact that std::shared_ptr
has an implicit constructor from std::nullptr_t
: 事实上std::shared_ptr
有一个来自std::nullptr_t
的隐式构造std::nullptr_t
:
§20.7.2.2 [util.smartptr.shared] p1
constexpr shared_ptr(nullptr_t) : shared_ptr() { }
This also allows for oddities like this: 这也允许像这样的奇怪:
#include <memory>
void f(std::shared_ptr<int>){}
int main(){
f(42 - 42);
}
You can only assign a shared pointer to another instance of a shared pointer. 您只能将共享指针分配给共享指针的另一个实例。 Assigning the type the shared_pointer holds is not possible. 无法分配shared_pointer保留的类型。 Afaik this is the only overload for the operator: Afaik这是运营商唯一的超载:
shared_ptr& operator=(const shared_ptr& r);
What you are doing is assigning 0 (which in this case equals NULL) to the pointer, not the value of the type. 你正在做的是将0(在这种情况下等于NULL)分配给指针,而不是类型的值。 You type is not even initialized at this point in the code. 您在此代码中甚至未对类型进行初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.