我有一个头文件foo.h
像这样(无关的东西省略):
#pragma once
#include <memory>
class Bar;
struct Foo
{
std::shared_ptr<Bar> getBar();
std::shared_ptr<const Bar> getBar() const
{
return const_cast<Foo*>(this)->getBar();
}
};
的非常量重载getBar()
是在 .cpp 文件中实现的,该文件还可以看到完整的定义Bar
.
When foo.h
包含在另一个文件中(该文件看不到定义Bar
),VS 2010 给了我这样的警告:
warning C4150: deletion of pointer to incomplete type 'Bar'; no destructor called
关于 const 重载getBar()
(或者实际上是在标准库深处从该重载实例化的东西上)。
我的问题是是否可以安全地忽略该警告。
在我看来,有两个成员函数std::shared_ptr<Bar>
被叫进来getBar() const
:转换构造函数和析构函数。
// converting constructor
template <class Y>
std::shared_ptr<const Bar>::shared_ptr(std::shared_ptr<Y> &&r)
这用于初始化返回值getBar() const
从返回值getBar()
。这没有列出任何需要的先决条件(C++11 27.2.2.1 §20-22)Y
(Bar
就我而言)是完整的。
// destructor
std::shared_ptr<const Bar>::~shared_ptr()
27.2.2.2 §1 规定,当被销毁的共享指针为空时,没有副作用。
我明白为什么我收到警告 - 析构函数代码还必须关心以下情况:delete
必须在存储的指针上调用,并且此代码确实会删除不完整的类型。但在我看来,在我的情况下它永远无法达到,所以getBar() const
是安全的。
我是否正确,或者我是否忽略了一个电话或可能使getBar() const
真的删除一个不完整的类型吗?