避免调用move构造函数 [英] Avoid calling move constructor

查看:58
本文介绍了避免调用move构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例

#include <cstdint>

class FooC
{
public:
   FooC(uint16_t iPort, uint16_t iPin)
   : PORT(iPort)
   , PIN(iPin)
   {
   };

   ~FooC() = default;

   FooC() = delete;
   FooC(const FooC&) = delete;
   FooC(FooC&&) = delete;

private:
   const uint16_t PORT;
   const uint16_t PIN;
};

int main()
{
    FooC array[2] = {
       FooC(1,2),
       FooC(3,4)
    };
}

我不想调用默认,移动和复制构造函数。因此,我删除了功能。不幸的是,这导致以下错误(与C ++ 11一起编译)

and I don't want to call the default, move and copy constructor. Due to that I deleted the functions. Unfortunately this results in following error (compiled with C++11)


:在函数'int main()'中:

: In function 'int main()':

:28:5:错误:使用已删除的功能'FooC :: FooC(FooC&&)'

:28:5: error: use of deleted function 'FooC::FooC(FooC&&)'

 };

 ^

:16:4:注意:在此处声明

:16:4: note: declared here

FooC(FooC&&) = delete;

^~~~

:28:5:错误:使用删除函数'FooC :: FooC(FooC&&)'

:28:5: error: use of deleted function 'FooC::FooC(FooC&&)'

 };

 ^

:16:4:注意:在此处声明

:16:4: note: declared here

FooC(FooC&&) = delete;

^~~~

编译器返回:1

在此示例中是否可以强制使用参数调用构造函数,并且仍然删除默认的,移动并复制的构造函数?

Is it possible to force in this example the calling of constructor with the parameters and still delete the default, move and copy constructor?

推荐答案

在C ++ 11和C ++ 14中,可以使用嵌套的花括号:

In C++11 and C++14, you can use nested braces:

FooC array[2] = {{1,2}, {3,4}};

在C ++ 17中,由于有了新的prvalue /物化规则,您的代码应该已经可以正常工作了( 保证复制省略)。

In C++17 your code should already work as written thanks to the new prvalue/materialization rules ("guaranteed copy elision").

这篇关于避免调用move构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆