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

时间:2015-03-21 12:52:10

标签: c++ c++11 clang++

考虑这段代码

#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,

我的问题是它是编译器错误还是非确认代码?

1 个答案:

答案 0 :(得分:1)

首先,clang 3.5.0(不是Apple的)编译你的例子,所以你的特定版本或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