克隆 (编程)

计算机科学中,“克隆”指对一个对象制作一个完全相同的副本,其常常在基于原型编程中的编程范型或者面向对象程序设计(OOP)中用到。

浅拷贝

在大多数编程语言中(但除了:Ruby等一些语言),例如doublefloatintlong等一些原始型別仅仅将它们的值存储于计算机内存中的某处(通常为调用栈中)。给它进行一次简单赋值,你可以将变量的内容复制到另外一个变量中:

在Java或C++中进行基本类型的复制:

int original = 42;
int copy = 0;

copy = original;

许多OOP编程语言(包括JavaD語言ECMAScriptC♯)利用对象引用。对象引用与其他语言中的指针类似,其使得对象可以被指针所传递而完整的对象不被复制。

以下是在Java语言中的范例,当使用简单赋值“拷贝”一个对象时:

Object original = new Object();
Object copy = null;

copy = original; // 不复制对象仅仅复制其引用

这段代码并没有复制对象,变量“original”与“copy”实际上指向相同的对象。在C++中,以下是相同效果代码:

Object* original = new Object();
Object* copy = NULL;
copy = original;

这段代码指明复制对象的是一个“指针”,而非对象本身。

克隆过程

制造与对象相同的一个副本而非仅仅制造它的引用的过程被称为克隆。在大多数编程语言中,编程语言和库可以便利一些克隆的过程。在Java语言中,Object类包含了clone()方法英语Clone (Java method),此方法仅仅复制对象并返回一个指向被复制对象的引用。由于此方法位于Object类中,程序员得以在所有定义于Java的类中使用克隆方法(虽然为了正常使用,其需要根据其应用于不同的层级进行改写)。

在Java语言中进行对象的克隆:

Object originalObj = new Object();
Object copyObj = null;

copyObj = originalObj.clone(); // 复制对象并分配一个指向“copyObj”的引用

一般而言,C++中的对象像基本类型一样运行,所以复制一个C++对象可以使用“=”(分配)赋值运算符。C++语言中所有的类中存在一个默认的赋值运算符,但其效果可能被运算符重载所影响。使用此方法时可能存在危险(参见对象切片英语Object slicing)。防止对象切片的方法的方法之一是使用与Java所有的类中的clone()方法来实现,并使用指针(请注意C++中不存在自带的clone()方法)。

C++中对象克隆的示例:

Object originalObj;
Object copyObj(originalObj); // 创建名为copyObj的originalObj拷贝

C++中使用指针进行对象克隆的示例(防止对象切片请参见[1]):

Object* originalObj = new Object;
Object* copyObj = nullptr;

copyObj = new Object(*originalObj); // 创建originalObj的拷贝并将其地址分配给copyObj

参考文献

  1. ^ 参见en.allexperts.com页面存档备份,存于互联网档案馆)的问答(Q&A)部分

Read other articles:

Agonis flexuosa Status konservasiRisiko rendahIUCN177372293 TaksonomiDivisiTracheophytaSubdivisiSpermatophytesKladAngiospermaeKladmesangiospermsKladeudicotsKladcore eudicotsKladSuperrosidaeKladrosidsKladmalvidsOrdoMyrtalesFamiliMyrtaceaeGenusAgonisSpesiesAgonis flexuosa Sweet, 1830 Tata namaBasionimMetrosideros flexuosa (en) lbs Agonis flexuosa adalah sebuah spesies pohon yang tumbuh di barat daya Australia Barat. Tumbuhan tersebut merupakan spesies Agonis paling umum, dan salah satu pohon pa...

 

Arranged ability to borrow money For the 2014 Georgian film, see Line of Credit (film). This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Line of credit – news · newspapers · books · scholar · JSTOR (September 2014) (Learn how and when to remove this template message) Part of a series onFinance Markets Assets ...

 

Italian football club Football clubGelbisonFull nameGelbison Cilento Vallo della LucaniaFounded1956GroundStadio Giovanni Morra,Vallo della Lucania, ItalyCapacity2,250ChairmanMaurizio PuglisiManagerGianluca EspositoLeagueSerie D Group H2022–23Serie C Group C, 18thh of 20 (relegated) Home colours Away colours Gelbison Cilento Vallo della Lucania,[1] commonly known as Gelbison, is an Italian association football club located in Vallo della Lucania, Campania. Gelbison currently plays in...

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (يوليو 2016) منتخب يوغوسلافيا تحت 21 سنة لكرة القدم بلد الرياضة يوغوسلافيا  الفئة كرة قدم تحت 21 سنة للرجال  [لغات...

 

Indonesian chicken noodle dish Bakmi ayamBakmi ayam with mushroom, chinese cabbage and chicken broth soup.Alternative namesMi ayam cincang, bakmi ayam, Chicken noodlesCourseMain coursePlace of originIndonesia[1]Region or stateNationwideAssociated cuisineIndonesiaServing temperatureHotMain ingredientsNoodle, chicken meat, soy sauce, garlic, cooking oil (from chicken fat or vegetable oil), chicken broth, chinese cabbage, scallionsFood energy(per serving)1 bowl of mie ayam contains 500 c...

 

Lanterne de Rochecorbon Type Château-fort Début construction XIe siècle Protection  Classé MH (1840)[1] Coordonnées 47° 24′ 33″ nord, 0° 45′ 19″ est Pays France Anciennes provinces de France Touraine Région Centre-Val de Loire Département Indre-et-Loire Commune Rochecorbon Géolocalisation sur la carte : France Lanterne de Rochecorbon Géolocalisation sur la carte : Centre-Val de Loire Lanterne de Rochecorbon Géolocalis...

拉吉夫·甘地राजीव गांधीRajiv Gandhi1987年10月21日,拉吉夫·甘地在阿姆斯特丹斯希普霍尔机场 第6任印度总理任期1984年10月31日—1989年12月2日总统吉亞尼·宰爾·辛格拉马斯瓦米·文卡塔拉曼前任英迪拉·甘地继任維什瓦納特·普拉塔普·辛格印度對外事務部部長任期1987年7月25日—1988年6月25日前任Narayan Dutt Tiwari(英语:Narayan Dutt Tiwari)继任納拉辛哈·拉奥任期1984年10�...

 

「アプリケーション」はこの項目へ転送されています。英語の意味については「wikt:応用」、「wikt:application」をご覧ください。 この記事には複数の問題があります。改善やノートページでの議論にご協力ください。 出典がまったく示されていないか不十分です。内容に関する文献や情報源が必要です。(2018年4月) 古い情報を更新する必要があります。(2021年3月)出...

 

Čukarica ЧукарицаMunisipalitas Lambang kebesaranLokasi Čukarica di kota BeogradNegara SerbiaKotaBeogradStatusMunisipalitasPermukiman8Pemerintahan • JenisMunisipalitas Beograd • Kepala MunisipalitasSrđan Kolarić (SNS)Luas • Total157 km2 (61 sq mi)Populasi (2011) • Total179,031 • Kepadatan1.155/km2 (2,990/sq mi)Zona waktuUTC+1 (CET) • Musim panas (DST)UTC+2 (CEST)Kode pos11030Kode a...

Solid form of resin For other uses, see Rosin (disambiguation). This article's lead section may be too short to adequately summarize the key points. Please consider expanding the lead to provide an accessible overview of all important aspects of the article. (April 2023) A cake of rosin, made for use by violinists. Rosin (/ˈrɒzɪn/), also called colophony or Greek pitch (Latin: pix graeca), is a solid form of resin obtained from pines and some other plants, mostly conifers, produced by heat...

 

  Lihat Bahasa Manchu di: ISO  • Ethnologue  • Wikipedia bahasa Inggris Bahasa Manchu ᠮᠠᠨ᠋ᠵᡠᡤᡳᠰᡠᠨ manju gisun Dituturkan diTiongkokWilayahHeilongjiangPenutur60[1] Rumpun bahasaTungusik Tungusik SelatanJurchenikManchu Kode bahasaISO 639-2mncISO 639-3mncLINGUIST List mncGlottologmanc1252[2]IETFmncELPManchu Status pemertahanan C10Kategori 10Kategori ini menunjukkan bahwa bahasa telah punah (Extinct)C9Kategori 9Kategori ini menun...

 

Louis IIIRaja Francia Barat (Prancis)Dua halaman pertama dari salinan awal Ludwigslied, sebuah lagu yang ditulis selama kehidupan raja, merayakan kemenangannya atas bangsa Viking di SaucourtBerkuasa879–882PrancisSeptember 879PendahuluLouis IIPenerusCarloman IIPemakamanBasilika Santo DenisWangsaCarolingia Louis III (863/65 – 5 Agustus 882) merupakan seorang Raja Prancis, yang pada saat itu masih disebut Francia Barat, dari tahun 879 sampai kematiannya. Putra kedua Louis yang Gagap dan istr...

Political party in Estonia You can help expand this article with text translated from the corresponding article in Estonian. (July 2023) Click [show] for important translation instructions. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipedia. Do not translate text that...

 

Sinistra Italiana PresidenteNichi Vendola[1] SegretarioNicola Fratoianni[2] Stato Italia SedeCorso del Rinascimento, 69 00186 Roma AbbreviazioneSI Fondazione7 novembre 2015 (movimento)19 febbraio 2017 (partito) Derivato daSinistra Ecologia LibertàFuturo a Sinistra IdeologiaSocialismo democratico[3][4]Ecosocialismo[3]Progressismo[4]Antifascismo[4][5]Europeismo moderato[4][6] CollocazioneSinistra[...

 

Ra

Ancient Egyptian solar deity This article is about the Egyptian deity. For other uses, see Ra (disambiguation). RaIn one of his many forms, Ra, god of the Sun, has the head of a falcon and the sun-disk inside the Uraeus resting on his head.Name in hieroglyphs or or Major cult centerHeliopolis but was worshipped everywhere in Ancient Egypt.SymbolSun DiskGenealogyParentsNone (most accounts)Khnum and Neith (alternative sources)Hathor (In the cycle of rebirth) Mehet-Weret (some accounts)SiblingsA...

v · mLes communes les plus peuplées de la région Auvergne-Rhône-Alpes(plus de 20 000 habitants - population municipale en 2020) Plus de 100 000 habitants Annecy Clermont-Ferrand Grenoble Lyon Saint-Étienne Villeurbanne Plus de 40 000 habitants Bourg-en-Bresse Bron Caluire-et-Cuire Chambéry Saint-Priest Valence Vaulx-en-Velin Vénissieux Plus de 30 000 habitants Aix-les-Bains Annemasse Échirolles Meyzieu Montélimar Montluçon Oullins-Pierre-Bénite Rillie...

 

Independent federal government agency (1947–1975) United States Atomic Energy CommissionSeal of the AECIndependent agency overviewFormed1946Dissolved1975Superseding agencyEnergy Research and Development Administration (ERDA)Nuclear Regulatory Commission (NRC)HeadquartersWashington, D.C. (1947–1957)Germantown, Maryland (1958–1975)[1] The United States Atomic Energy Commission (AEC) was an agency of the United States government established after World War II by the U.S. Congress t...

 

Technical university in Russia Volga State University of TechnologyПоволжский государственный технологический университетMottoТрадиции, качество, перспектива (Russian)Motto in EnglishTraditions, quality, perspectiveTypePublicEstablished1932RectorViktor ShebashevLocation Yoshkar-Ola, Russia56°37′49.90″N 47°53′34.75″E / 56.6305278°N 47.8929861°E / 56.6305278; 47.8929861Colours&...

Chu Lệ đổi hướng tới đây. Đối với Chu Lệ vương, xem Chu Lệ vương. Minh Thành Tổ明成祖Hoàng đế Trung Hoa (chi tiết...)Chân dung Đại Minh Thành Tổ Văn Hoàng ĐếHoàng đế Đại MinhTrị vì17 tháng 7 năm 1402 – 12 tháng 8 năm 1424(22 năm, 26 ngày)Tiền nhiệmMinh Huệ TôngKế nhiệmMinh Nhân TôngThông tin chungSinh12 tháng 4 năm Chí Chính thứ 20 nhà Nguyên tức (1360-05-02)2 tháng 5 năm 1360 dương l...

 

Sir Thomas WyattThomas Wyatt, yang digambar oleh Hans Holbein the YoungerLahirThomas Wyatt1503Allington Castle, KentMeninggal06 Oktober 1542 (umur 38–39)Clifton Maybank House, DorsetMakamSherborne Abbey, DorsetPekerjaanPenyair InggrisSuami/istriElizabeth BrookeAnakSir Thomas WyattHenryFrancisEdwardOrang tuaSir Henry WyattAnne Skinner Sir Thomas Wyatt adalah seorang penyair yang memperkenalkan soneta Italia, terza rima berbentuk bait serta syair Prancis ke dalam sastra Inggris.[...