小编Tri*_*ian的帖子

自动生成的移动构造函数,不具有可移动成员

我遇到了一个非常有趣的情况,因为我正在编写的代码编译,即使我很惊讶它也是如此,我想请你接受.

情况就是这样.我有一个删除了移动和复制构造函数的类,它有用户定义的赋值运算符:

struct A {
    A() { }
    A(const A&) = delete;
    A(A&& ) = delete;

    A& operator=(const A& ) { return *this; }
    A& operator=(A&& ) { return *this; }
};
Run Code Online (Sandbox Code Playgroud)

我还有另一个班级A作为唯一的成员.在这个类中我定义了复制构造函数,但我将移动构造函数保留为默认值,并通过调用swap函数定义赋值运算符:

class B{
public:
    A a;

    B()
    : a{}
    { }

    B(const B&)
    : a{}
    { }

    B(B&& other) = default;
};

int main() {
    B b1;
    B b2(std::move(b1)); // compiles??
}
Run Code Online (Sandbox Code Playgroud)

为什么默认移动构造函数工作,考虑到它不能简单地调用移动或复制构造函数A?我使用的是gcc 4.8.4.

c++ move-semantics c++11

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

返回从字符串文字创建的静态 string_view 是否安全?

我有一个相对简单的用例:我想将一个特征关联到一个类,该类将返回一些用户定义的字符串,即一些用户定义的注册 ID。由于这个注册应该在编译时定义,我希望它是 constexpr,所以我写了如下内容:

template <typename T>
struct ClassRegistration
{
    static constexpr std::string_view
    Name();
};

template <>                                                                                    
struct ClassRegistration<int>                                                            
{                                                                                              
    static constexpr std::string_view                                                        
    Name()                                                                                     
    {                                                                                          
        return std::string_view{ "int" };                                                     
    }                                                                                          
};
Run Code Online (Sandbox Code Playgroud)

https://godbolt.org/z/5p8xkA

一切正常,但由于 string_view 实际上并不拥有它的缓冲区,我想知道它是否保证安全,我不只是指一个悬空指针。从我读到的字符串文字保证具有与程序本身一样长的生命周期(从这个函数返回的字符串文字的SO Lifetime)。

因此,string_view 的这种用法是否安全合适?

c++ string-literals constexpr string-view c++17

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