如何使用指针的结构复制到里面(使复制指针和数据,他们指向)的数据? [英] How to copy a structure with pointers to data inside (so to copy pointers and data they point to)?

查看:101
本文介绍了如何使用指针的结构复制到里面(使复制指针和数据,他们指向)的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这样

struct GetResultStructure
{
  int length;
  char* ptr;
};

我需要一个能让它的一个完整副本这意味着我需要一个副本有新的PTR poinnting上的数据我在原来的结构中进行复制的结构。这是任何可能如何?我的意思是任何结构,我有一个包含师生比将与它的长度一些领域,我需要将由lengthes的给定数组......它的任何很酷提升功能我应对结构的师生比的所有数据和它们指向复制到功能?或者有什么办法如何创建这样的功能?

I need a way to make a full copy of it meaning I need a copy to have a structure with new ptr poinnting on to copy of data I had in original structure. Is It any how possible? I mean any structure I have which contains ptrs will have some fields with its lengths I need a function that would copy my structure coping all ptrs and data they point to by given array of lengthes... Any cool boost function for it? Or any way how to create such function?

推荐答案

有关你所描述的特定方案,使用的std ::矢量或其它序列容器。如果这样做,那么简单地复制类型的对象 GetResultStructure 将副本所指向的数据以及

For the specific scenario you describe, use a std::vector or some other sequence container. If you do so, then simply copying objects of type GetResultStructure will make copies of the pointed-to data as well:

struct GetResultStructure {
    std::vector<char> data;
};

GetResultStructure a = GetData();
GetResultStructure b = a; // a and b have distinct, equivalent data vectors

在一般情况下,当你确实需要这个工具你自己,你通过实现一个拷贝构造函数和拷贝赋值操作符这样做。要做到这一点最简单的方法是使用复制和交换成语,涵盖非常详细的什么是复制和交换成语?

In general, when you do need to implement this yourself, you do so by implementing a copy constructor and a copy assignment operator. The easiest way to do that is to use the copy-and-swap idiom, covered in great detail in What is the copy-and-swap idiom?

这篇关于如何使用指针的结构复制到里面(使复制指针和数据,他们指向)的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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