在clang++上使用带有enable_shared_from_this的shared_ptr时编译错误

Compile errors while using shared_ptr with enable_shared_from_this on clang++

本文关键字:shared this from 错误 编译 ptr enable clang++      更新时间:2023-10-16

考虑这段代码

#include <memory>
class FooBar :  public std::enable_shared_from_this<FooBar>{};
typedef std::shared_ptr<const FooBar> ConstantPointer;
int main()
{
  ConstantPointer  p(new FooBar());
  return 0;
}

在g++版本4.7.4上,当使用-std=c++11选项时,它编译起来没有问题

关于clang++版本Apple LLVM 6.0版(clang-600.0.57)(基于LLVM 3.5svn)

它会生成以下编译错误

In file included from main.cpp:1:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:4013:35: error: no viable overloaded '='
                __e->__weak_this_ = *this;
                ~~~~~~~~~~~~~~~~~ ^ ~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:4050:5: note: in instantiation of function template specialization
      'std::__1::shared_ptr<const FooBar>::__enable_weak_this<FooBar>' requested here
    __enable_weak_this(__p);
    ^
main.cpp:8:20: note: in instantiation of function template specialization 'std::__1::shared_ptr<const FooBar>::shared_ptr<FooBar, void>' requested here
  ConstantPointer  p(new FooBar());
                   ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:4942:15: note: candidate function not viable: no known conversion from
      'std::__1::shared_ptr<const FooBar>' to 'const std::__1::weak_ptr<FooBar>' for 1st argument
    weak_ptr& operator=(weak_ptr const& __r) _NOEXCEPT;
              ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:4949:9: note: candidate template ignored: could not match 'weak_ptr' against 'shared_ptr'
        operator=(weak_ptr<_Yp> const& __r) _NOEXCEPT;
        ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:4967:13: note: candidate template ignored: disabled by 'enable_if' [with _Yp = const FooBar]
            is_convertible<_Yp*, element_type*>::value,

我的问题是,这是编译器错误还是未确认的代码?

首先,clang 3.5.0(不是苹果的)编译了您的示例,所以您的clang的特定版本或安装似乎有问题。

其次,我相信您的示例格式良好,定义良好,因为标准没有指定所属shared_ptr实例(示例中为p)的确切类型参数:

[util.smartptr.enab]/7

shared_ptr<T> shared_from_this();
shared_ptr<T const> shared_from_this() const;

要求:enable_shared_from_this<T>应为T的可访问基类。*this应当是类型为T的对象t的子对象至少有一个shared_ptr实例p拥有&t