【问题标题】:Brace initialization prevents non-const use of temporary大括号初始化防止非常量使用临时
【发布时间】:2017-08-25 15:24:55
【问题描述】:

我想创建一个 const 对象的临时副本并以非常量的方式使用它:

struct S {
    S& f() { return *this; }
};

int main() {
    const S a{};
    S{a}.f(); // Error on this line
    return 0;
}

使用 msvc (Visual Studio 2017, C++14),我得到这个错误:

错误 C2662 'S &S::f(void)': 无法将 'this' 指针从 'const S' 转换为 'S &'

如果我将大括号初始化更改为经典初始化,它会起作用:

S{a}.f(); // Does not work
S(a).f(); // Works

这两种变体都可以在 gcc 中正常编译。我错过了什么还是这是一个编译器错误?

【问题讨论】:

  • 您使用哪个版本的 C++ 来编译您的代码?假设 C++11
  • fyi g++ 5.1.0 编译正常
  • 那是MSVC给你的:
  • @Elyasin 我将其编译为 C++14

标签: c++ temporary list-initialization


【解决方案1】:

它看起来像一个编译器错误,或者是奇怪优化的结果,因为这种原始代码的变体只会使 ctors 和 dtor 产生副作用,使用 MSVC 可以很好地编译:

#include <iostream>

struct S {
    S(const S& other) {
        std::cout << "Copy ctor " << &other << " -> " << this << std::endl;
    }
    S() {
        std::cout << "Default ctor " << this << std::endl;
    }
    ~S() {
        std::cout << "Dtor " << this << std::endl;
    }
    S& f() { return *this; }
};

int main() {
    const S a{};
    std::cout << &a << std::endl;
    S{a}.f();
    return 0;
}

编译成功,输出为:

Default ctor 0306FF07
Copy ctor 0306FF07 -> 0306FF06
Dtor 0306FF06
Dtor 0306FF07

【讨论】:

    【解决方案2】:

    似乎是另一个 MSVC 错误。

    S{a} 被推导出为const struct S,仅此而已。

    #include <string>
    #include <iostream>
    
    template < class T >
    std::string type_name()
    {
        std::string p = __FUNCSIG__;
        return p.substr( 106, p.length() - 106 - 7 );
    }
    
    
    struct S {
        S& f() { return *this; }
    };
    
    int main() {
        const S a{};
        //S{a}.f(); // Error on this line
        std::cout << type_name<decltype(S{a})>() << std::endl;
        return 0;
    }
    

    输出:

    const struct S
    

    【讨论】:

    • 如果您能提供 link为什么 这是一个错误,我将不胜感激。
    • @Elyasin 这是一个错误,因为根本不应该有类型推导。直接列表初始化不推断类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 2015-10-21
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多