小编lor*_*rro的帖子

一个类不能有自己的静态constexpr成员实例吗?

这段代码给了我不完整的类型错误.问题是什么?一个类不允许拥有自己的静态成员实例吗?有没有办法达到同样的效果?

struct Size
{
    const unsigned int width;
    const unsigned int height;

    static constexpr Size big = { 480, 240 };

    static constexpr Size small = { 210, 170 };

private:

    Size( ) = default;
};
Run Code Online (Sandbox Code Playgroud)

c++ static-members c++11

41
推荐指数
3
解决办法
3194
查看次数

C++在const向量成员的初始化列表中嵌入lambda

我有一个类,其const vector成员拥有对某些对象的唯一指针.构造时,sequence对象应该窃取传递给构造函数的唯一指针向量的所有权,以便序列对象现在是向量参数中唯一指针所拥有的对象的所有者.

class sequence
{
    const std::vector< std::unique_ptr< statement > > m_statements;

    sequence( std::vector< std::unique_ptr< statement > > & statements );
};
Run Code Online (Sandbox Code Playgroud)

我第一次尝试实现构造函数时,执行了以下操作:

sequence::sequence( vector< unique_ptr< statement > > & statements )
    m_statements( statements )
{
}
Run Code Online (Sandbox Code Playgroud)

但是当然这不能编译,因为一个人不能复制构造一个unique_ptr因此不能复制构造一个vector.

C++不允许在构造函数体中初始化const成员(就像Java对最终成员一样),但仅在初始化列表中.因此,一种可能的解决方案可以是删除const修饰符,m_statement并使用循环将内容从构造函数的主体中的一个向量移动到另一个向量.

但我想保留这个const修饰符.

所以我提出了另一种似乎可以编译的解决方案,但是因为我是C++ 11的新手,所以我不确定它是什么样的.我的想法是将上面描述的循环嵌入到lambda函数中,这样我就可以m_statement使用循环在初始化列表中初始化并仍然保持const修改符m_statement.

sequence::sequence( vector< unique_ptr< const statement > > & statements ) :
    m_statements(([ & statements ] {
        vector< unique_ptr< …
Run Code Online (Sandbox Code Playgroud)

c++ const unique-ptr move-semantics c++11

1
推荐指数
1
解决办法
372
查看次数

标签 统计

c++ ×2

c++11 ×2

const ×1

move-semantics ×1

static-members ×1

unique-ptr ×1