在这种情况下 unique_ptr 的行为应该是什么?
假设我有以下内容:
std::unique_ptr<A> pA;
pA(new A);
在这个复杂的示例中,pA(new A);
的行为应该是什么?
据我所知,在 MSVC2010 中,default_delete 中的 void operator()(T*) const; 在 new
返回后立即调用,并立即删除指针。而 g++(4.7.0) 给了我 no match for call (std::unique_ptr)(A*)
错误。
Say I have the following:
std::unique_ptr<A> pA;
pA(new A);
In this convoluted example, what should the behavior of pA(new A);
be?
As far as I can tell, in MSVC2010, void operator()(T*) const;
from default_delete is called right after new
returns and deletes the pointer right away. Whereas g++(4.7.0) gave me no match for call (std::unique_ptr<A>)(A*)
error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该代码不应编译。
std::unique_ptr
不会重载operator()
。Visual C++ 2011 开发者预览版正确地拒绝了该代码。 Visual C++ 2010 仅接受代码,因为 其
std::unique_ptr
实现中存在错误。The code should not compile.
std::unique_ptr
does not overloadoperator()
.The Visual C++ 2011 Developer Preview rightly rejects the code. Visual C++ 2010 only accepts the code due to a bug in its
std::unique_ptr
implementation.MSVC 对unique_ptr 采用无状态删除器优化,即它利用空基类优化并仅从删除器继承。不幸的是,继承是
public
,这就是为什么您可以访问default_delete
函子的重载operator()
。MSVC employs the state-less deleter optimization for
unique_ptr
, i.e. it exploits the empty-base-class-optimization and just inherits from the deleter. Unfortunately, the inheritance ispublic
, which is why you have access to the overloadedoperator()
of thedefault_delete
functor.