【问题标题】:"chosen constructor is explicit in copy-initialization error" with clang++ 4.2使用clang ++ 4.2的“选择的构造函数在复制初始化错误中是显式的”
【发布时间】:2013-06-20 06:52:30
【问题描述】:

我有 clang++ 4.2

Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin11.4.2
Thread model: posix

当我尝试编译这段 c++11 代码时:

class ContextSummary {
    int id;
    int hops;
    std::map<std::string, int> db {};
    std::time_t timestamp;

ContextSummary(int id, const std::map<std::string, int>& db = {}, int hops = 3, std::time_t timestamp = 0)
{
    this->id = id;
    this->db = db;
    this->hops = hops;
    this->timestamp = timestamp;
}

我收到此错误消息。该代码适用于 g++4.8

error: 
      chosen constructor is explicit in copy-initialization
  ...id, const std::map<std::string, int>& db = {}, int hops = 3, std::time_t...

                                           ^    ~~

这是 clang++ 错误吗?如何绕过此错误?

【问题讨论】:

  • 您正在尝试获取对临时值的引用。您用作默认参数的空映射仅对构造函数的调用是临时的。
  • @JoachimPileborg 如果this-&gt;db 是地图的实例——而不是地图的引用,这应该不是问题. @prosseef BTW,您应该在构造函数中使用初始化列表。不是矫揉造作。

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


【解决方案1】:

复制我在评论中所说的话

这是http://cplusplus.github.io/LWG/lwg-active.html#2193。我不确定“提议的解决方案”或类似的东西是否会使其成为 C++14。在复制初始化上下文中使用显式默认构造函数进行值初始化是否格式正确的事实本身也是核心语言 DR http://open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1518 ,它解释了可能的交叉编译器差异。

如果您的实现实现 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1494 并且以下将是您可以完成的默认参数的有效语法

const std::map<std::string, int>& db{}

不幸的是,这是不允许的(我认为我的原因是显式传递一个参数,你也不能直接初始化一个参数,那么为什么允许它作为默认参数呢?)。所以在我看来唯一的方法是显式创建它

const std::map<std::string, int>& db = std::map<std::string, int>{}

决定是否要以可能更多的代码为代价来摆脱冗余。一些替代品

const std::map<std::string, int>& db = decltype(ContextSummary::db){}
const std::map<std::string, int>& db_ = decltype(db){}
const std::map<std::string, int>& db = std::decay<decltype(db)>::type{}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    相关资源
    最近更新 更多