我们可以通过值从函数返回具有删除/私有复制/移动构造函数的对象吗? [英] Can we return objects having a deleted/private copy/move constructor by value from a function?

查看:156
本文介绍了我们可以通过值从函数返回具有删除/私有复制/移动构造函数的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 03中,不可能通过值返回具有私有非定义复制构造函数的类的对象:

In C++03 it is impossible to return an object of a class having a private non-defined copy constructor by value:

struct A { A(int x) { ... } private: A(A const&); };

A f() {
  return A(10); // error!
  return 10;    // error too!
}



我想知道,这个限制在C ++ 11中解除,可能写入具有类类型返回类型的类的函数没有用于复制或移动的构造函数?我记得允许函数的调用者使用新返回的对象,但是他们不能复制值并存储在某个地方可能是有用的。

I was wondering, was this restriction lifted in C++11, making it possible to write functions having a class type return type for classes without constructors used for copy or move? I remember it could be useful to allow callers of a function use the newly returned object, but that they are not able to copy the value and store it somewhere.

推荐答案

这是它如何工作

A f() {
  return { 10 };
}

即使 A 没有工作副本或移动构造函数,也没有其他构造函数可以复制或移动 A

This works even though A has no working copy or move constructor and no other constructor that could copy or move an A!

利用C ++ 11的这个特性,构造函数(在这种情况下 int )必须是非显式的。

To make use of this feature of C++11, the constructor (taking int in this case) has to be non-explicit though.

这篇关于我们可以通过值从函数返回具有删除/私有复制/移动构造函数的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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