詳解C++值多態(tài)中的傳統(tǒng)多態(tài)與類(lèi)型擦除
引言
我有一個(gè)顯示屏模塊:

模塊上有一個(gè)128*64的單色顯示屏,一個(gè)單片機(jī)(B)控制它顯示的內(nèi)容。單片機(jī)的I²C總線(xiàn)通過(guò)四邊上的排針排母連接到其他單片機(jī)(A)上,A給B發(fā)送指令,B繪圖。
B可以向屏幕逐字節(jié)發(fā)送顯示數(shù)據(jù),但是不能讀取,所以程序中必須設(shè)置顯存。一幀需要1024字節(jié),但是單片機(jī)B只有512字節(jié)內(nèi)存,其中只有256字節(jié)可以分配為顯存。解決這個(gè)問(wèn)題的方法是在B的程序中把顯示屏分成4個(gè)區(qū)域,保存所有要繪制的圖形的信息,每次在256字節(jié)中繪制1/4屏,分批繪制、發(fā)送。
簡(jiǎn)而言之,我需要維護(hù)多個(gè)類(lèi)型的數(shù)據(jù)。稍微具體點(diǎn),我要把它們放在一個(gè)類(lèi)似于數(shù)組的結(jié)構(gòu)中,然后遍歷數(shù)組,繪制每一個(gè)元素。
不同的圖形,用相同的方式來(lái)對(duì)待,這是繼承與多態(tài)的最佳實(shí)踐。我可以設(shè)計(jì)一個(gè)Shape類(lèi),定義virtual void draw() const = 0;,每收到一個(gè)指令就new一個(gè)Line、Rectangle等類(lèi)型的對(duì)象出來(lái),放入std::vector<Shape*>中,在遍歷中對(duì)每個(gè)Shape*指針調(diào)用->draw()。
但是對(duì)不起,今天我跟new杠上了。單片機(jī)程序注重運(yùn)行時(shí)效率,除了初始化以外,沒(méi)事最好別瞎new。每個(gè)指令new一下,清屏指令一起delete,恐怕不大合適吧!
我需要值多態(tài),一種不需要指針或引用,通過(guò)對(duì)象本身就可以表現(xiàn)出的多態(tài)。
背景
我得先介紹一點(diǎn)知識(shí),一些剛上完C++入門(mén)課程的新手不可能了解的,卻是深入C++底層和體會(huì)C++設(shè)計(jì)思想所必需的知識(shí),正因?yàn)橛辛诉@些知識(shí)我才能想出“值多態(tài)”然后把它實(shí)現(xiàn)出來(lái)。如果你對(duì)這些知識(shí)了如指掌,或是已經(jīng)迫不及待地想知道我是怎么實(shí)現(xiàn)值多態(tài)的,可以直接拉到下面實(shí)現(xiàn)一節(jié)。
多態(tài)
多態(tài),是指為不同類(lèi)型的實(shí)體提供統(tǒng)一的接口,或用相同的符號(hào)來(lái)代表多種不同的類(lèi)型。C++里有很多種多態(tài):

先說(shuō)編譯期多態(tài)。非模板函數(shù)重載是一種多態(tài),用相同的名字調(diào)用的函數(shù)可能是不同的,取決于參數(shù)類(lèi)型。如果你需要一個(gè)函數(shù)名字能夠多處理一種類(lèi)型,你就得多寫(xiě)一個(gè)重載,這樣的多態(tài)是封閉式多態(tài)。好在新的重載不用和原有的函數(shù)寫(xiě)在一起。
模板是一種開(kāi)放式多態(tài)——適配一種新的類(lèi)型是對(duì)那個(gè)新的類(lèi)型提要求,而模板是不改動(dòng)的。相比于后文中的運(yùn)行時(shí)多態(tài),C++鼓勵(lì)模板,“STL”的“T”就足以說(shuō)明這一點(diǎn)。瞧,標(biāo)準(zhǔn)庫(kù)的算法都是模板函數(shù),而不是像《設(shè)計(jì)模式》中那樣讓各種迭代器繼承自Iterator<T>基類(lèi)。
模板多態(tài)的弊端在于模板參數(shù)T類(lèi)型的對(duì)象必須是即取即用的,函數(shù)返回以后就沒(méi)了,不能持久地維護(hù)。如果需要,那得使用類(lèi)型擦除。
運(yùn)行時(shí)多態(tài)大致可以分為繼承一套和類(lèi)型擦除一套,它們都是開(kāi)放式多態(tài)。繼承、虛函數(shù)這些東西,又稱(chēng)OOP,我在本文標(biāo)題中稱(chēng)之為“傳統(tǒng)多態(tài)”,我認(rèn)為是沒(méi)有異議的。面向?qū)ο缶幊陶Z(yǔ)言的四個(gè)特點(diǎn),抽象、封裝、繼承、多態(tài),大家都熟記于心(有時(shí)候少了抽象),以致于有些人說(shuō)到多態(tài)就是虛函數(shù)。的確,很多程序中廣泛使用繼承,但既然function/bind已經(jīng)“救贖”了,那就要學(xué)它們、用它們,還要學(xué)它們的設(shè)計(jì)和思想,在合理范圍內(nèi)取代繼承這一套工具,因?yàn)樗鼈兊拇_有很多問(wèn)題——“蝙蝠是鳥(niǎo)也是獸,水上飛機(jī)能飛也能游”,多重繼承、虛繼承、各種overhead……連Lippman都看不下去了:

繼承的另一個(gè)主要問(wèn)題,也是本文主要針對(duì)的問(wèn)題,是多態(tài)需要一層間接,即指針或引用。仍然以迭代器為例,如果begin方法返回一個(gè)指向新new出來(lái)的Iterator<T>對(duì)象的指針,客戶(hù)在使用完迭代器后還得記得把它delete掉,或者用std::lock_guard一般的RAII類(lèi)來(lái)負(fù)責(zé)迭代器的delete工作,總之需要多操一份心。
因此在現(xiàn)代C++中,基于類(lèi)型擦除的多態(tài)逐漸占據(jù)了上風(fēng)。類(lèi)型擦除是用一個(gè)類(lèi)來(lái)包裝多種具有相似接口的對(duì)象,在功能上屬于多態(tài)包裝器,如std::function就是一個(gè)多態(tài)函數(shù)包裝器,原計(jì)劃在C++20中標(biāo)準(zhǔn)化的polymorphic_value是一個(gè)多態(tài)值包裝器——與我的意圖很接近。后面會(huì)詳細(xì)討論這些。
私以為,這兩種運(yùn)行時(shí)多態(tài),只有語(yǔ)義上的不同。
虛函數(shù)的實(shí)現(xiàn)
《深度探索C++對(duì)象模型》中最吸引人的部分莫過(guò)于虛函數(shù)的實(shí)現(xiàn)了。盡管C++標(biāo)準(zhǔn)對(duì)于虛函數(shù)的實(shí)現(xiàn)方法沒(méi)有作出任何規(guī)定和假設(shè),但是用指向虛函數(shù)表(vtable)的指針來(lái)實(shí)現(xiàn)多態(tài)是這個(gè)小圈子里心照不宣的秘密。
假設(shè)有兩個(gè)類(lèi):
class Base
{
public:
Base(int i) : i(i) { }
virtual ~Base() { }
virtual void func() const {
std::cout << "Base: " << i << std::endl;
}
private:
int i;
};
class Derived : public Base
{
public:
Derived(int i, int j)
: Base(i), j(j) { }
virtual ~Derived() { }
virtual void func() const override {
std::cout << "Derived: " << j << std::endl;
}
private:
int j;
};
這兩個(gè)類(lèi)的實(shí)例在內(nèi)存中的布局可能是這樣:

如果你把一個(gè)Derived實(shí)例的指針賦給Base*的變量,然后調(diào)用func(),程序會(huì)把這個(gè)指針指向的對(duì)象當(dāng)作Base的實(shí)例,解引用它的第二格,在vtable中下標(biāo)為2的位置找到func的函數(shù)指針,然后把this指針傳入調(diào)用它。雖然被當(dāng)成Base實(shí)例,但該對(duì)象的vtable實(shí)際指向的是Derived類(lèi)的vtable,因此被調(diào)用的函數(shù)是Derived::func,基于繼承的多態(tài)就是這樣實(shí)現(xiàn)的。
而如果你把一個(gè)Derived實(shí)例賦給Base變量,只有i會(huì)被拷貝,vtable會(huì)初始化成Base的vtable,j則被丟掉了。調(diào)用它的func,Base::func會(huì)執(zhí)行,而且很可能是直接而非通過(guò)函數(shù)指針調(diào)用的。
這種實(shí)現(xiàn)可以推及到繼承樹(shù)(強(qiáng)調(diào)“樹(shù)”,即單繼承)的情況。至于多重繼承中的指針偏移和虛繼承中的子對(duì)象指針,過(guò)于復(fù)雜,我就不介紹了。
vtable指針不拷貝是虛函數(shù)指針語(yǔ)義的罪魁禍?zhǔn)祝贿^(guò)這也是不得已而為之的,拷貝vtable指針會(huì)引來(lái)更大的麻煩:如果Base實(shí)例中有Derived虛函數(shù)表指針,調(diào)用func就會(huì)訪(fǎng)問(wèn)該對(duì)象的第三格,但第三格是無(wú)效的內(nèi)存空間。相比之下,把維護(hù)指針的任務(wù)交給程序員是更好的選擇。
類(lèi)型擦除
不拷貝vtable就不能實(shí)現(xiàn)值語(yǔ)義,拷貝vtable又會(huì)有訪(fǎng)問(wèn)的問(wèn)題,那么是什么原因?qū)е铝诉@個(gè)問(wèn)題呢?是因?yàn)?code>Base和Derived實(shí)例的大小不同。實(shí)現(xiàn)了類(lèi)型擦除的類(lèi)也使用了與vtable相同或類(lèi)似的多態(tài)實(shí)現(xiàn),而作為一個(gè)而非多個(gè)類(lèi),類(lèi)型擦除類(lèi)的大小是確定的,因此可以拷貝vtable或其類(lèi)似物,也就可以實(shí)現(xiàn)值語(yǔ)義。C++想方設(shè)法讓類(lèi)類(lèi)型表現(xiàn)得像內(nèi)置類(lèi)型一樣,這是類(lèi)型擦除更深刻的意義。
類(lèi)型擦除,顧名思義,就是把對(duì)象的類(lèi)型擦除掉,讓你在不知道它的類(lèi)型的情況下對(duì)它執(zhí)行一些操作。舉個(gè)例子,std::function有一個(gè)帶約束的模板構(gòu)造函數(shù),你可以用它來(lái)包裝任何參數(shù)類(lèi)型匹配的可調(diào)用對(duì)象,在構(gòu)造函數(shù)結(jié)束后,不光是你,std::function也不知道它包裝的是什么類(lèi)型的實(shí)例,但是operator()就可以調(diào)用那個(gè)可調(diào)用對(duì)象。我在一篇文章中剖析過(guò)std::function的實(shí)現(xiàn),當(dāng)然它還有很多種實(shí)現(xiàn)方法,其他類(lèi)型擦除類(lèi)的實(shí)現(xiàn)也都大同小異,它們都包含兩個(gè)要素:可能帶約束的模板構(gòu)造函數(shù),以及函數(shù)指針,無(wú)論是可見(jiàn)的(直接維護(hù))還是不可見(jiàn)的(使用繼承)。
為了獲得更真切的感受,我們來(lái)寫(xiě)一個(gè)最簡(jiǎn)單的類(lèi)型擦除:
class MyFunction
{
private:
class FunctorWrapper
{
public:
virtual ~FunctorWrapper() = default;
virtual FunctorWrapper* clone() const = 0;
virtual void call() const = 0;
};
template<typename T>
class ConcreteWrapper : public FunctorWrapper
{
public:
ConcreteWrapper(const T& functor)
: functor(functor) { }
virtual ~ConcreteWrapper() override = default;
virtual ConcreteWrapper* clone() const
{
return new ConcreteWrapper(*this);
}
virtual void call() const override
{
functor();
}
private:
T functor;
};
public:
MyFunction() = default;
template<typename T>
MyFunction(T&& functor)
: ptr(new ConcreteWrapper<T>(functor)) { }
MyFunction(const MyFunction& other)
: ptr(other.ptr->clone()) { }
MyFunction& operator=(const MyFunction& other)
{
if (this != &other)
{
delete ptr;
ptr = other.ptr->clone();
}
return *this;
}
MyFunction(MyFunction&& other) noexcept
: ptr(std::exchange(other.ptr, nullptr)) { }
MyFunction& operator=(MyFunction&& other) noexcept
{
if (this != &other)
{
delete ptr;
ptr = std::exchange(other.ptr, nullptr);
}
return *this;
}
~MyFunction()
{
delete ptr;
}
void operator()() const
{
if (ptr)
ptr->call();
}
FunctorWrapper* ptr = nullptr;
};
MyFunction類(lèi)中維護(hù)一個(gè)FunctorWrapper指針,它指向一個(gè)ConcreteWrapper<T>實(shí)例,調(diào)用虛函數(shù)來(lái)實(shí)現(xiàn)多態(tài)。虛函數(shù)有析構(gòu)、clone和call三個(gè),它們分別用于MyFunction的析構(gòu)、拷貝和函數(shù)調(diào)用。
類(lèi)型擦除類(lèi)的實(shí)現(xiàn)中總會(huì)保留一點(diǎn)類(lèi)型信息。MyFunction類(lèi)中關(guān)于T的類(lèi)型信息表現(xiàn)在FunctorWrapper的vtable中,本質(zhì)上是函數(shù)指針。類(lèi)型擦除類(lèi)也可以跳過(guò)繼承的工具,直接使用函數(shù)指針實(shí)現(xiàn)多態(tài)。無(wú)論使用哪種實(shí)現(xiàn),類(lèi)型擦除類(lèi)總是可以被拷貝或移動(dòng)或兩者兼有,多態(tài)性可以由對(duì)象本身體現(xiàn)。
不是每一滴牛奶都叫特侖蘇,也不是每一個(gè)類(lèi)的實(shí)例都能被MyFunction包裝。MyFunction對(duì)T的要求是可以拷貝、可以用operator()() const調(diào)用,這些稱(chēng)為類(lèi)型T的“affordance”。說(shuō)到affordance,普通的模板函數(shù)也對(duì)模板類(lèi)型有affordance,比如std::sort要求迭代器可以隨機(jī)存取,否則編譯器會(huì)給你一堆冗長(zhǎng)的錯(cuò)誤信息。C++20引入了concept和requires子句,對(duì)編譯器和程序員都是有好處的。
每個(gè)類(lèi)型擦除類(lèi)的affordance都在寫(xiě)成的時(shí)候確定下來(lái)。affordance被要求的方式不是繼承某個(gè)基類(lèi),而只看你這個(gè)類(lèi)是否有相應(yīng)的方法,就像Python那樣,只要函數(shù)接口匹配上就可以了。這種類(lèi)型識(shí)別方式稱(chēng)為“duck typing”,來(lái)源于“duck test”,意思是“If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck”。
類(lèi)型擦除類(lèi)要求的affordance通常都是一元的,也就是成員函數(shù)的參數(shù)中不含T,比如對(duì)于包裝整數(shù)的類(lèi),你可以要求T + 42,但是無(wú)法要求T + U,一個(gè)類(lèi)型擦除類(lèi)的實(shí)例是不知道另一個(gè)屬于同一個(gè)類(lèi)但是構(gòu)造自不同類(lèi)型對(duì)象的實(shí)例的信息的。我覺(jué)得這條規(guī)則有一個(gè)例外,operator==是可以想辦法支持的。
MyFunction類(lèi)雖然實(shí)現(xiàn)了值多態(tài),但還是使用了new和delete語(yǔ)句。如果可調(diào)用對(duì)象只是一個(gè)簡(jiǎn)單的函數(shù)指針,是否有必要在堆上開(kāi)辟空間?
SBO
小的對(duì)象保存在類(lèi)實(shí)例中,大的對(duì)象交給堆并在實(shí)例中維護(hù)指針,這種技巧稱(chēng)為小緩沖優(yōu)化(Small Buffer Optimization, SBO)。大多數(shù)類(lèi)型擦除類(lèi)都應(yīng)該使用SBO以節(jié)省內(nèi)存并提升效率,問(wèn)題在于SBO與繼承不共存,維護(hù)每個(gè)實(shí)例中的一個(gè)vtable或幾個(gè)函數(shù)指針是件挺麻煩的事,還會(huì)拖慢編譯速度。
但是在內(nèi)存和性能面前,這點(diǎn)工作量能叫事嗎?
class MyFunction
{
private:
static constexpr std::size_t size = 16;
static_assert(size >= sizeof(void*), "");
struct Data
{
Data() = default;
char dont_use[size];
} data;
template<typename T>
static void functorConstruct(Data& dst, T&& src)
{
using U = typename std::decay<T>::type;
if (sizeof(U) <= size)
new ((U*)&dst) U(std::forward<U>(src));
else
*(U**)&dst = new U(std::forward<U>(src));
}
template<typename T>
static void functorDestructor(Data& data)
{
using U = typename std::decay<T>::type;
if (sizeof(U) <= size)
((U*)&data)->~U();
else
delete *(U**)&data;
}
template<typename T>
static void functorCopyCtor(Data& dst, const Data& src)
{
using U = typename std::decay<T>::type;
if (sizeof(U) <= size)
new ((U*)&dst) U(*(const U*)&src);
else
*(U**)&dst = new U(**(const U**)&src);
}
template<typename T>
static void functorMoveCtor(Data& dst, Data& src)
{
using U = typename std::decay<T>::type;
if (sizeof(U) <= size)
new ((U*)&dst) U(*(const U*)&src);
else
*(U**)&dst = std::exchange(*(U**)&src, nullptr);
}
template<typename T>
static void functorInvoke(const Data& data)
{
using U = typename std::decay<T>::type;
if (sizeof(U) <= size)
(*(U*)&data)();
else
(**(U**)&data)();
}
template<typename T>
static void (*const vtables[4])();
void (*const* vtable)() = nullptr;
public:
MyFunction() = default;
template<typename T>
MyFunction(T&& obj)
: vtable(vtables<T>)
{
functorConstruct(data, std::forward<T>(obj));
}
MyFunction(const MyFunction& other)
: vtable(other.vtable)
{
if (vtable)
((void (*)(Data&, const Data&))vtable[1])(this->data, other.data);
}
MyFunction& operator=(const MyFunction& other)
{
this->~MyFunction();
vtable = other.vtable;
new (this) MyFunction(other);
return *this;
}
MyFunction(MyFunction&& other) noexcept
: vtable(std::exchange(other.vtable, nullptr))
{
if (vtable)
((void (*)(Data&, Data&))vtable[2])(this->data, other.data);
}
MyFunction& operator=(MyFunction&& other) noexcept
{
this->~MyFunction();
new (this) MyFunction(std::move(other));
return *this;
}
~MyFunction()
{
if (vtable)
((void (*)(Data&))vtable[0])(data);
}
void operator()() const
{
if (vtable)
((void (*)(const Data&))vtable[3])(this->data);
}
};
template<typename T>
void (*const MyFunction::vtables[4])() =
{
(void (*)())MyFunction::functorDestructor<T>,
(void (*)())MyFunction::functorCopyCtor<T>,
(void (*)())MyFunction::functorMoveCtor<T>,
(void (*)())MyFunction::functorInvoke<T>,
};
(如果你能完全看懂這段代碼,說(shuō)明你的C語(yǔ)言功底非常扎實(shí)!如果看不懂,實(shí)現(xiàn)中有一個(gè)可讀性更好的版本。)
現(xiàn)在的MyFunction類(lèi)就充當(dāng)了原來(lái)的FunctorWrapper,用vtable實(shí)現(xiàn)多態(tài)性。每當(dāng)MyFunction實(shí)例被賦以一個(gè)可調(diào)用對(duì)象時(shí),vtable被初始化為指向vtables<T>,用于T類(lèi)型的vtable(這里用到了C++14的變量模板)的指針。vtable中包含4個(gè)函數(shù)指針,分別進(jìn)行T實(shí)例的析構(gòu)、拷貝、移動(dòng)和調(diào)用。
以析構(gòu)函數(shù)functorDestructor<T>為例,U是T經(jīng)std::decay后的類(lèi)型,用于處理函數(shù)轉(zhuǎn)換為函數(shù)指針等情況。MyFunction類(lèi)中定義了size字節(jié)的空間data,用于存放小的可調(diào)用對(duì)象或大的可調(diào)用對(duì)象的指針之一,functorDestructor<T>知道具體是哪種情況:當(dāng)sizeof(U) <= size時(shí),data存放可調(diào)用對(duì)象本身,把data解釋為U并調(diào)用其析構(gòu)函數(shù)~U();當(dāng)sizeof(U) > size時(shí),data存放指針,把data解釋為U*并delete它。其他函數(shù)原理相同,注意new ((U*)&dst) U(std::forward<U>(src));是定位new語(yǔ)句。
除了參數(shù)為T的構(gòu)造函數(shù)以外,MyFunction的其他成員函數(shù)都通過(guò)vtable來(lái)調(diào)用T的方法,因?yàn)樗鼈兌疾恢?code>T是什么。在拷貝時(shí),與FunctorWrapper子類(lèi)的實(shí)例被裁剪不同,MyFunction的vtable一起被拷貝,依然實(shí)現(xiàn)了值多態(tài)——還避免了一部分new,符合我的意圖。但是這還沒(méi)有結(jié)束。
polymorphic_value
polymorphic_value是一個(gè)實(shí)現(xiàn)了值多態(tài)的類(lèi)模板,原定于在C++20中標(biāo)準(zhǔn)化,但是C++20沒(méi)有收錄,預(yù)計(jì)會(huì)進(jìn)入C++23標(biāo)準(zhǔn)(那時(shí)候我還寫(xiě)不寫(xiě)C++都不一定呢)。到目前為止,我對(duì)polymorphic_value源碼的理解還處于一知半解的狀態(tài),只能簡(jiǎn)要地介紹一下。
polymorphic_value的模板參數(shù)T是一個(gè)類(lèi)類(lèi)型,任何T、T的子類(lèi)U、polymorphic_value<U>的實(shí)例都可以用來(lái)構(gòu)造polymorphic_value對(duì)象。polymorphic_value對(duì)象可以拷貝,其中的值也被拷貝,并且可以傳播const(通過(guò)const polymorphic_value得到的是const T&),這使它區(qū)別于unique_ptr和shared_ptr;polymorphic_value又與類(lèi)型擦除不同,因?yàn)樗鹬乩^承,沒(méi)有使用duck typing。
然而,一個(gè)從2017年開(kāi)始的,添加SBO的issue,一直沒(méi)有人回復(fù)——這反映出polymorphic_value的實(shí)現(xiàn)并不簡(jiǎn)單——目前的版本中,無(wú)論對(duì)象的大小,polymorphic_value總會(huì)new一個(gè)control_block出來(lái);對(duì)于從一個(gè)不同類(lèi)型的polymorphic_value構(gòu)造出的實(shí)例,還會(huì)出現(xiàn)指針套指針的情況(delegating_control_block),對(duì)運(yùn)行時(shí)性能有很大影響。個(gè)人認(rèn)為,SBO可以把兩個(gè)問(wèn)題一并解決,這也側(cè)面反映出繼承工具存在的問(wèn)題。
接口
我要實(shí)現(xiàn)3個(gè)類(lèi):Shape,值多態(tài)的基類(lèi);Line,包含4個(gè)整數(shù)作為坐標(biāo),用于演示SBO的第一種情形;Rectangle,包含4個(gè)整數(shù)和一個(gè)bool值,后者指示矩形是否填充,用于演示第二種情形。它們的行為要像STL中的類(lèi)一樣,有默認(rèn)構(gòu)造函數(shù)、析構(gòu)函數(shù)、拷貝、移動(dòng)構(gòu)造和賦值、swap,還要支持operator==和draw。operator==在兩參數(shù)類(lèi)型不同時(shí)返回false,相同時(shí)比較其內(nèi)容;draw是一個(gè)多態(tài)的函數(shù),在演示程序中輸出圖形的信息。
一個(gè)簡(jiǎn)單的實(shí)現(xiàn)是用std::function加上適配器:
#include <iostream>
#include <functional>
#include <new>
struct Point
{
int x;
int y;
};
std::ostream& operator<<(std::ostream& os, const Point& point)
{
os << point.x << ", " << point.y;
return os;
}
class Shape
{
private:
template<typename T>
class Adapter
{
public:
Adapter(const T& shape)
: shape(shape) { }
void operator()() const
{
shape.draw();
}
private:
T shape;
};
public:
template<typename T>
Shape(const T& shape)
: function(Adapter<T>(shape)) { }
void draw() const
{
function();
}
private:
std::function<void()> function;
};
class Line
{
public:
Line() { }
Line(Point p0, Point p1)
: endpoint{ p0, p1 } { }
Line(const Line&) = default;
Line& operator=(const Line&) = default;
void draw() const
{
std::cout << "Drawing a line: " << endpoint[0] << "; " << endpoint[1]
<< std::endl;
}
private:
Point endpoint[2];
};
class Rectangle
{
public:
Rectangle() { }
Rectangle(Point v0, Point v1, bool filled)
: vertex{ v0, v1 }, filled(filled) { }
Rectangle(const Rectangle&) = default;
Rectangle& operator=(const Rectangle&) = default;
void draw() const
{
std::cout << "Drawing a rectangle: " << vertex[0] << "; " << vertex[1]
<< "; " << (filled ? "filled" : "blank") << std::endl;
}
private:
Point vertex[2];
bool filled;
};
下面的實(shí)現(xiàn)與這段代碼的思路是一樣的,但是更加“純粹”。
實(shí)現(xiàn)
#include <iostream>
#include <new>
#include <type_traits>
#include <utility>
struct Point
{
int x;
int y;
bool operator==(const Point& rhs) const
{
return this->x == rhs.x && this->y == rhs.y;
}
};
std::ostream& operator<<(std::ostream& os, const Point& point)
{
os << point.x << ", " << point.y;
return os;
}
class Shape
{
protected:
using FuncPtr = void (*)();
using FuncPtrCopy = void (*)(Shape*, const Shape*);
static constexpr std::size_t funcIndexCopy = 0;
using FuncPtrDestruct = void (*)(Shape*);
static constexpr std::size_t funcIndexDestruct = 1;
using FuncPtrCompare = bool (*)(const Shape*, const Shape*);
static constexpr std::size_t funcIndexCompare = 2;
using FuncPtrDraw = void (*)(const Shape*);
static constexpr std::size_t funcIndexDraw = 3;
static constexpr std::size_t funcIndexTotal = 4;
class ShapeData
{
public:
static constexpr std::size_t size = 16;
template<typename T>
struct IsLocal : std::integral_constant<bool,
(sizeof(T) <= size) && std::is_trivially_copyable<T>::value> { };
private:
char placeholder[size];
template<typename T, typename U = void>
using EnableIfLocal =
typename std::enable_if<IsLocal<T>::value, U>::type;
template<typename T, typename U = void>
using EnableIfHeap =
typename std::enable_if<!IsLocal<T>::value, U>::type;
public:
ShapeData() { }
template<typename T, typename... Args>
EnableIfLocal<T> construct(Args&& ... args)
{
new (reinterpret_cast<T*>(this)) T(std::forward<Args>(args)...);
}
template<typename T, typename... Args>
EnableIfHeap<T> construct(Args&& ... args)
{
this->access<T*>() = new T(std::forward<Args>(args)...);
}
template<typename T>
EnableIfLocal<T> destruct()
{
this->access<T>().~T();
}
template<typename T>
EnableIfHeap<T> destruct()
{
delete this->access<T*>();
}
template<typename T>
EnableIfLocal<T, T&> access()
{
return reinterpret_cast<T&>(*this);
}
template<typename T>
EnableIfHeap<T, T&> access()
{
return *this->access<T*>();
}
template<typename T>
const T& access() const
{
return const_cast<ShapeData*>(this)->access<T>();
}
};
Shape(const FuncPtr* vtable)
: vtable(vtable) { }
public:
Shape() { }
Shape(const Shape& other)
: vtable(other.vtable)
{
if (vtable)
reinterpret_cast<FuncPtrCopy>(vtable[funcIndexCopy])(this, &other);
}
Shape& operator=(const Shape& other)
{
if (this != &other)
{
if (vtable)
reinterpret_cast<FuncPtrDestruct>(vtable[funcIndexDestruct])
(this);
vtable = other.vtable;
if (vtable)
reinterpret_cast<FuncPtrCopy>(vtable[funcIndexCopy])
(this, &other);
}
return *this;
}
Shape(Shape&& other) noexcept
: vtable(other.vtable), data(other.data)
{
other.vtable = nullptr;
}
Shape& operator=(Shape&& other) noexcept
{
swap(other);
return *this;
}
~Shape()
{
if (vtable)
reinterpret_cast<FuncPtrDestruct>(vtable[funcIndexDestruct])(this);
}
void swap(Shape& other) noexcept
{
using std::swap;
swap(this->vtable, other.vtable);
swap(this->data, other.data);
}
bool operator==(const Shape& rhs) const
{
if (this->vtable == nullptr || this->vtable != rhs.vtable)
return false;
return reinterpret_cast<FuncPtrCompare>(vtable[funcIndexCompare])
(this, &rhs);
}
bool operator!=(const Shape& rhs) const
{
return !(*this == rhs);
}
void draw() const
{
if (vtable)
reinterpret_cast<FuncPtrDraw>(vtable[funcIndexDraw])(this);
}
protected:
const FuncPtr* vtable = nullptr;
ShapeData data;
template<typename T>
static void defaultCopy(Shape* dst, const Shape* src)
{
dst->data.construct<T>(src->data.access<T>());
}
template<typename T>
static void defaultDestruct(Shape* shape)
{
shape->data.destruct<T>();
}
template<typename T>
static bool defaultCompare(const Shape* lhs, const Shape* rhs)
{
return lhs->data.access<T>() == rhs->data.access<T>();
}
};
namespace std
{
void swap(Shape& lhs, Shape& rhs) noexcept
{
lhs.swap(rhs);
}
}
class Line : public Shape
{
private:
struct LineData
{
Point endpoint[2];
LineData() { }
LineData(Point p0, Point p1)
: endpoint{ p0, p1 } { }
bool operator==(const LineData& rhs) const
{
return this->endpoint[0] == rhs.endpoint[0]
&& this->endpoint[1] == rhs.endpoint[1];
}
bool operator!=(const LineData& rhs) const
{
return !(*this == rhs);
}
};
static_assert(ShapeData::IsLocal<LineData>::value, "");
public:
Line()
: Shape(lineVtable)
{
data.construct<LineData>();
}
Line(Point p0, Point p1)
: Shape(lineVtable)
{
data.construct<LineData>(p0, p1);
}
Line(const Line&) = default;
Line& operator=(const Line&) = default;
Line(Line&&) = default;
Line& operator=(Line&&) = default;
~Line() = default;
private:
static const FuncPtr lineVtable[funcIndexTotal];
static ShapeData& accessData(Shape* shape)
{
return static_cast<Line*>(shape)->data;
}
static const ShapeData& accessData(const Shape* shape)
{
return accessData(const_cast<Shape*>(shape));
}
static void lineDraw(const Shape* line)
{
auto& data = static_cast<const Line*>(line)->data.access<LineData>();
std::cout << "Drawing a line: " << data.endpoint[0] << "; "
<< data.endpoint[1] << std::endl;
}
};
const Shape::FuncPtr Line::lineVtable[] =
{
reinterpret_cast<Shape::FuncPtr>(Shape::defaultCopy<LineData>),
reinterpret_cast<Shape::FuncPtr>(Shape::defaultDestruct<LineData>),
reinterpret_cast<Shape::FuncPtr>(Shape::defaultCompare<LineData>),
reinterpret_cast<Shape::FuncPtr>(Line::lineDraw),
};
class Rectangle : public Shape
{
private:
struct RectangleData
{
Point vertex[2];
bool filled;
RectangleData() { }
RectangleData(Point v0, Point v1, bool filled)
: vertex{ v0, v1 }, filled(filled) { }
bool operator==(const RectangleData& rhs) const
{
return this->vertex[0] == rhs.vertex[0]
&& this->vertex[1] == rhs.vertex[1]
&& this->filled == rhs.filled;
}
bool operator!=(const RectangleData& rhs) const
{
return !(*this == rhs);
}
};
static_assert(!ShapeData::IsLocal<RectangleData>::value, "");
public:
Rectangle()
: Shape(rectangleVtable)
{
data.construct<RectangleData>();
}
Rectangle(Point v0, Point v1, bool filled)
: Shape(rectangleVtable)
{
data.construct<RectangleData>(v0, v1, filled);
}
Rectangle(const Rectangle&) = default;
Rectangle& operator=(const Rectangle&) = default;
Rectangle(Rectangle&&) = default;
Rectangle& operator=(Rectangle&&) = default;
~Rectangle() = default;
private:
static const FuncPtr rectangleVtable[funcIndexTotal];
static ShapeData& accessData(Shape* shape)
{
return static_cast<Rectangle*>(shape)->data;
}
static const ShapeData& accessData(const Shape* shape)
{
return accessData(const_cast<Shape*>(shape));
}
static void rectangleDraw(const Shape* rect)
{
auto& data = accessData(rect).access<RectangleData>();
std::cout << "Drawing a rectangle: " << data.vertex[0] << "; "
<< data.vertex[1] << "; " << (data.filled ? "filled" : "blank")
<< std::endl;
}
};
const Shape::FuncPtr Rectangle::rectangleVtable[] =
{
reinterpret_cast<Shape::FuncPtr>(Shape::defaultCopy<RectangleData>),
reinterpret_cast<Shape::FuncPtr>(Shape::defaultDestruct<RectangleData>),
reinterpret_cast<Shape::FuncPtr>(Shape::defaultCompare<RectangleData>),
reinterpret_cast<Shape::FuncPtr>(Rectangle::rectangleDraw),
};
template<typename T>
Shape test(const T& s0)
{
s0.draw();
T s1 = s0;
s1.draw();
T s2;
s2 = s1;
s2.draw();
Shape s3 = s0;
s3.draw();
Shape s4;
s4 = s0;
s4.draw();
Shape s5 = std::move(s0);
s5.draw();
Shape s6;
s6 = std::move(s5);
s6.draw();
return s6;
}
int main()
{
Line line({ 1, 2 }, { 3, 4 });
auto l2 = test(line);
Rectangle rect({ 5, 6 }, { 7, 8 }, true);
auto r2 = test(rect);
std::swap(l2, r2);
l2.draw();
r2.draw();
}
對(duì)象模型
之前提到,傳統(tǒng)多態(tài)與類(lèi)型擦除的本質(zhì)是相同的,都使用了函數(shù)指針,放在vtable或?qū)ο笾?。?code>Shape的繼承體系中,Line和Rectangle都是具體的類(lèi),寫(xiě)兩個(gè)vtable非常容易,所以我采用了vtable的實(shí)現(xiàn)。
Line和Rectangle繼承自Shape,為了在值拷貝時(shí)不被裁剪,三個(gè)類(lèi)的內(nèi)存布局必須相同,也就是說(shuō)Line和Rectangle不能定義新的數(shù)據(jù)成員。Shape預(yù)留了16字節(jié)空間供子類(lèi)使用,存儲(chǔ)Line的數(shù)據(jù)或指向Rectangle數(shù)據(jù)的指針,后者是我特意安排用于演示的(兩個(gè)static_assert只是為了確保演示到位,并非我對(duì)兩個(gè)子類(lèi)的內(nèi)存布局有什么假設(shè))。

SBO類(lèi)型
ShapeData是Shape中的數(shù)據(jù)空間,儲(chǔ)存值或指針由ShapeData和數(shù)據(jù)類(lèi)型共同決定,如果把決定的任務(wù)交給具體的數(shù)據(jù)類(lèi)型,ShapeData是很難修改大小的,因此我把ShapeData設(shè)計(jì)為一個(gè)帶有模板函數(shù)的類(lèi)型,以數(shù)據(jù)類(lèi)型為模板參數(shù)T,提供構(gòu)造、析構(gòu)、訪(fǎng)問(wèn)的操作,各有兩個(gè)版本,具體調(diào)用哪個(gè)可以交給編譯器來(lái)決定,從而提高程序的可維護(hù)性。
std::function同樣使用SBO,在閱讀其源碼時(shí)我發(fā)現(xiàn),兩種情形的分界線(xiàn)可以不只是數(shù)據(jù)類(lèi)型的大小,還有is_trivially_copyable等,這樣做的好處是移動(dòng)和swap可以使用接近默認(rèn)的行為。
class ShapeData
{
public:
static constexpr std::size_t size = 16;
static_assert(size >= sizeof(void*), "");
template<typename T>
struct IsLocal : std::integral_constant<bool,
(sizeof(T) <= size) && std::is_trivially_copyable<T>::value> { };
private:
char placeholder[size];
template<typename T, typename U = void>
using EnableIfLocal =
typename std::enable_if<IsLocal<T>::value, U>::type;
template<typename T, typename U = void>
using EnableIfHeap =
typename std::enable_if<!IsLocal<T>::value, U>::type;
public:
ShapeData() { }
template<typename T, typename... Args>
EnableIfLocal<T> construct(Args&& ... args)
{
new (reinterpret_cast<T*>(this)) T(std::forward<Args>(args)...);
}
template<typename T, typename... Args>
EnableIfHeap<T> construct(Args&& ... args)
{
this->access<T*>() = new T(std::forward<Args>(args)...);
}
template<typename T>
EnableIfLocal<T> destruct()
{
this->access<T>().~T();
}
template<typename T>
EnableIfHeap<T> destruct()
{
delete this->access<T*>();
}
template<typename T>
EnableIfLocal<T, T&> access()
{
return reinterpret_cast<T&>(*this);
}
template<typename T>
EnableIfHeap<T, T&> access()
{
return *this->access<T*>();
}
template<typename T>
const T& access() const
{
return const_cast<ShapeData*>(this)->access<T>();
}
};
EnableIfLocal和EnableIfHeap用了SFNIAE的技巧(這里有個(gè)類(lèi)似的例子)。我習(xí)慣用SFINAE,如果你愿意的話(huà)也可以用tag dispatch。
虛函數(shù)表
C99標(biāo)準(zhǔn)6.3.2.3 clause 8:
A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.
言下之意是所有函數(shù)指針大小相同。C++標(biāo)準(zhǔn)沒(méi)有這樣的規(guī)定,但是我作出這種假設(shè)(成員函數(shù)指針不包含在內(nèi))。據(jù)我所知,在所有的主流平臺(tái)中,這種假設(shè)都是成立的。于是,我定義類(lèi)型using FuncPtr = void (*)();,以FuncPtr數(shù)組為vtable,可以存放任意類(lèi)型的函數(shù)指針。
vtable中存放4個(gè)函數(shù)指針,它們分別負(fù)責(zé)對(duì)象的拷貝(沒(méi)有移動(dòng))、析構(gòu)、比較(operator==)和draw。函數(shù)指針的類(lèi)型各不相同,但是與子類(lèi)無(wú)關(guān),可以在Shape中定義,簡(jiǎn)化后面的代碼。每個(gè)函數(shù)指針的下標(biāo)顯然不能用0、1、2等magic number,也在Shape中定義了常量,方便維護(hù)。與default關(guān)鍵字類(lèi)似地,Shape提供了前三個(gè)函數(shù)的默認(rèn)實(shí)現(xiàn),絕大多數(shù)情況下不用另寫(xiě)。
class Shape
{
protected:
using FuncPtr = void (*)();
using FuncPtrCopy = void (*)(Shape*, const Shape*);
static constexpr std::size_t funcIndexCopy = 0;
using FuncPtrDestruct = void (*)(Shape*);
static constexpr std::size_t funcIndexDestruct = 1;
using FuncPtrCompare = bool (*)(const Shape*, const Shape*);
static constexpr std::size_t funcIndexCompare = 2;
using FuncPtrDraw = void (*)(const Shape*);
static constexpr std::size_t funcIndexDraw = 3;
static constexpr std::size_t funcIndexTotal = 4;
// ...
public:
// ...
protected:
const FuncPtr* vtable = nullptr;
ShapeData data;
template<typename T>
static void defaultCopy(Shape* dst, const Shape* src)
{
dst->data.construct<T>(src->data.access<T>());
}
template<typename T>
static void defaultDestruct(Shape* shape)
{
shape->data.destruct<T>();
}
template<typename T>
static bool defaultCompare(const Shape* lhs, const Shape* rhs)
{
return lhs->data.access<T>() == rhs->data.access<T>();
}
};
方法適配
所有具有多態(tài)性質(zhì)的函數(shù)都得通過(guò)調(diào)用虛函數(shù)表中的函數(shù)來(lái)執(zhí)行操作,這包括析構(gòu)、拷貝構(gòu)造、拷貝賦值(沒(méi)有移動(dòng))、operator==和draw。
class Shape
{
protected:
// ...
Shape(const FuncPtr* vtable)
: vtable(vtable) { }
public:
Shape() { }
Shape(const Shape& other)
: vtable(other.vtable)
{
if (vtable)
reinterpret_cast<FuncPtrCopy>(vtable[funcIndexCopy])(this, &other);
}
Shape& operator=(const Shape& other)
{
if (this != &other)
{
if (vtable)
reinterpret_cast<FuncPtrDestruct>(vtable[funcIndexDestruct])
(this);
vtable = other.vtable;
if (vtable)
reinterpret_cast<FuncPtrCopy>(vtable[funcIndexCopy])
(this, &other);
}
return *this;
}
Shape(Shape&& other) noexcept
: vtable(other.vtable), data(other.data)
{
other.vtable = nullptr;
}
Shape& operator=(Shape&& other) noexcept
{
swap(other);
return *this;
}
~Shape()
{
if (vtable)
reinterpret_cast<FuncPtrDestruct>(vtable[funcIndexDestruct])(this);
}
void swap(Shape& other) noexcept
{
using std::swap;
swap(this->vtable, other.vtable);
swap(this->data, other.data);
}
bool operator==(const Shape& rhs) const
{
if (this->vtable == nullptr || this->vtable != rhs.vtable)
return false;
return reinterpret_cast<FuncPtrCompare>(vtable[funcIndexCompare])
(this, &rhs);
}
bool operator!=(const Shape& rhs) const
{
return !(*this == rhs);
}
void draw() const
{
if (vtable)
reinterpret_cast<FuncPtrDraw>(vtable[funcIndexDraw])(this);
}
protected:
// ...
};
namespace std
{
void swap(Shape& lhs, Shape& rhs) noexcept
{
lhs.swap(rhs);
}
}
拷貝構(gòu)造函數(shù)拷貝vtable和數(shù)據(jù),析構(gòu)函數(shù)銷(xiāo)毀數(shù)據(jù),拷貝賦值函數(shù)先析構(gòu)再拷貝。operator==先檢查兩個(gè)參數(shù)的vtable是否相同,只有相同,兩個(gè)參數(shù)才是同一類(lèi)型,才能進(jìn)行后續(xù)比較。draw調(diào)用vtable中的對(duì)應(yīng)函數(shù)。所有方法都會(huì)先檢查vtable是否為nullptr,因?yàn)?code>Shape是一個(gè)抽象類(lèi)的角色,一個(gè)Shape對(duì)象是空的,任何操作都不執(zhí)行。
比較特殊的是移動(dòng)和swap。由于ShapeData data中存放的是is_trivially_copyable的數(shù)據(jù)類(lèi)型或指針,都是“位置無(wú)關(guān)”(可以trivially拷貝)的,因此swap中data可以直接復(fù)制。(swap在這么不trivial的情況下都能默認(rèn),給swap整一個(gè)運(yùn)算符不好嗎?)
移動(dòng)賦值把*this和other交換,把析構(gòu)*this的任務(wù)交給other。移動(dòng)構(gòu)造也相當(dāng)于swap,不過(guò)this->vtable == nullptr。其實(shí)我還可以寫(xiě)copy-and-swap:
Shape& operator=(Shape other)
{
swap(other);
return *this;
}
用以替換Shape& operator=(const Shape&)和Shape& operator=(Shape&&),可惜Shape& operator=(Shape)不屬于C++規(guī)定的特殊成員函數(shù),子類(lèi)不會(huì)繼承其行為。
子類(lèi)繼承以上所有函數(shù)。我非常想寫(xiě)上final以防止子類(lèi)覆寫(xiě),但是這些函數(shù)并不是C++語(yǔ)法上的虛函數(shù)。所以我們獲得了virtual的拷貝構(gòu)造和draw,實(shí)現(xiàn)了值多態(tài)。
討論
我翻開(kāi)C++標(biāo)準(zhǔn)一查,這標(biāo)準(zhǔn)沒(méi)有實(shí)現(xiàn)細(xì)節(jié),方方正正的每頁(yè)上都寫(xiě)著“undefined behavior”幾個(gè)詞。我橫豎睡不著,仔細(xì)看了半夜,才從字縫里看出字來(lái),滿(mǎn)本都寫(xiě)著一個(gè)詞是“trade-off”。如果要用一句話(huà)概括值多態(tài),那就是“更多義務(wù),更多權(quán)利”。
安全
Shape的實(shí)現(xiàn)代碼中充斥著強(qiáng)制類(lèi)型轉(zhuǎn)換,很容易引起對(duì)其類(lèi)型安全性的質(zhì)疑。這是多慮,因?yàn)?code>LineData和lineVtable是始終綁定在一起的,虛函數(shù)不會(huì)訪(fǎng)問(wèn)到非對(duì)應(yīng)類(lèi)型的數(shù)據(jù)。即使在這一點(diǎn)上出錯(cuò),只要數(shù)據(jù)類(lèi)型是比較trivial的(不包含指針之類(lèi)的),起碼程序不會(huì)崩潰。不過(guò)類(lèi)型安全性的前提是基類(lèi)與派生類(lèi)的大小相同,如果客戶(hù)違反了這一點(diǎn),那我只好使出C/C++傳統(tǒng)藝能——undefined behavior了。
類(lèi)型安全不等同于“類(lèi)型正確”——我隨便起的名字。在上面的演示程序中,如果我std::swap(line, rect),line就會(huì)存儲(chǔ)一個(gè)Rectangle實(shí)例,但line在語(yǔ)法上卻是一個(gè)Line實(shí)例!也就是說(shuō),Line和Rectangle只能在定義變量時(shí)保證類(lèi)型正確,在此之后它們就和Shape通假了。
類(lèi)型安全保證不會(huì)訪(fǎng)問(wèn)到非法的地址空間,那么內(nèi)存泄漏是否會(huì)發(fā)生?構(gòu)造時(shí)按照SBO的第二種情況new,而析構(gòu)時(shí)按照第一種情況trivially析構(gòu),這種情況是不可能發(fā)生的。首先前提是數(shù)據(jù)類(lèi)型與vtable配對(duì),在此基礎(chǔ)上vtable中拷貝與析構(gòu)配對(duì)。這些函數(shù)選擇哪個(gè)版本是在編譯期決定的,這更加讓人放心。
還有異常安全。只要客戶(hù)遵守一些異常處理的規(guī)則,使得Shape的析構(gòu)函數(shù)能夠被調(diào)用,就能確保不會(huì)有資源未釋放。
性能
空間上,值多態(tài)難免浪費(fèi)空間。預(yù)留的數(shù)據(jù)區(qū)域需要足夠大,才能存下大多數(shù)類(lèi)型的數(shù)據(jù),對(duì)于其中較小的有很多空間被浪費(fèi),對(duì)于大到放不進(jìn)的只存放一個(gè)指針,也是一種浪費(fèi)。富有創(chuàng)意的你還可以把一部分trivial的數(shù)據(jù)放在本地,其他的維護(hù)一個(gè)指針,但是那樣也太麻煩了吧。
時(shí)間上,值多態(tài)的動(dòng)態(tài)部分有更好的表現(xiàn)。相比于基于繼承的類(lèi)型擦除,值多態(tài)在創(chuàng)建對(duì)象時(shí)少一次new,使用時(shí)少一次解引用;相比于函數(shù)指針的類(lèi)型擦除,值多態(tài)在創(chuàng)建值多態(tài)只需維護(hù)一個(gè)vtable指針。相比于虛函數(shù),值多態(tài)的初衷就是避免new和delete。不過(guò),虛函數(shù)是編譯器負(fù)責(zé)的,編譯器要是有什么猥瑣優(yōu)化,那我認(rèn)輸。
但是值多態(tài)的靜態(tài)部分不盡人意。在傳統(tǒng)多態(tài)中,如果一個(gè)多態(tài)實(shí)例的類(lèi)型在編譯期可以確定,那么虛函數(shù)會(huì)靜態(tài)決議,不通過(guò)vtable而直接調(diào)用函數(shù)。在值多態(tài)中,子類(lèi)可以覆寫(xiě)基類(lèi)的普通“虛函數(shù)”,提升運(yùn)行時(shí)性能,但是對(duì)于拷貝控制函數(shù),無(wú)論子類(lèi)是否覆寫(xiě),編譯器總會(huì)調(diào)用基類(lèi)的對(duì)應(yīng)函數(shù),而它們的任務(wù)是多態(tài)拷貝,子類(lèi)沒(méi)有必要,有時(shí)也不能覆寫(xiě),更無(wú)法靜態(tài)決議了。不過(guò)考慮到line非Line的情況,還是老老實(shí)實(shí)用動(dòng)態(tài)決議吧。
時(shí)間和空間有權(quán)衡的余地。為了讓更多子類(lèi)的數(shù)據(jù)可以放在本地,基類(lèi)中的數(shù)據(jù)空間可以保留得大一些,但是也會(huì)浪費(fèi)更多空間;可以把vtable中的函數(shù)指針直接放在對(duì)象中,多占用一些空間,換來(lái)每次使用時(shí)減少一次解引用;拷貝、析構(gòu)和比較可以合并為一個(gè)函數(shù)以節(jié)省空間,但是需要多一個(gè)參數(shù)指明何種操作??傊瑐鹘y(tǒng)藝能implementation-defined。
擴(kuò)展
我要給Line加上一個(gè)子類(lèi)ThickLine,表示一定寬度的直線(xiàn)。在計(jì)算機(jī)的屏幕上繪制傾斜曲線(xiàn)常用Bresenham算法,我對(duì)它不太熟悉,希望程序能打印一些調(diào)試信息,所以給Line加上一個(gè)虛函數(shù)debug(而Rectangle繪制起來(lái)很容易)。當(dāng)然,不是C++語(yǔ)法上的虛函數(shù)。
class Line : public Shape
{
protected:
static constexpr std::size_t funcIndexDebug = funcIndexTotal;
using FuncPtrDebug = void (*)(const Line*);
static constexpr std::size_t funcIndexTotalLine = funcIndexTotal + 1;
struct LineData
{
Point endpoint[2];
LineData() { }
LineData(Point p0, Point p1)
: endpoint{ p0, p1 } { }
bool operator==(const LineData& rhs) const
{
return this->endpoint[0] == rhs.endpoint[0]
&& this->endpoint[1] == rhs.endpoint[1];
}
bool operator!=(const LineData& rhs) const
{
return !(*this == rhs);
}
};
Line(const FuncPtr* vtable)
: Shape(vtable) { }
public:
Line()
: Shape(lineVtable)
{
data.construct<LineData>();
}
Line(Point p0, Point p1)
: Shape(lineVtable)
{
data.construct<LineData>(p0, p1);
}
Line(const Line&) = default;
Line& operator=(const Line&) = default;
Line(Line&&) = default;
Line& operator=(Line&&) = default;
~Line() = default;
void debug() const
{
if (vtable)
reinterpret_cast<FuncPtrDebug>(vtable[funcIndexDebug])(this);
}
private:
static const FuncPtr lineVtable[funcIndexTotalLine];
static ShapeData& accessData(Shape* shape)
{
return static_cast<Line*>(shape)->data;
}
static const ShapeData& accessData(const Shape* shape)
{
return accessData(const_cast<Shape*>(shape));
}
static void lineDraw(const Shape* line)
{
auto& data = static_cast<const Line*>(line)->data.access<LineData>();
std::cout << "Drawing a line: " << data.endpoint[0] << "; "
<< data.endpoint[1] << std::endl;
}
static void lineDebug(const Line* line)
{
std::cout << "Line debug:\n\t";
lineDraw(line);
}
};
const Shape::FuncPtr Line::lineVtable[] =
{
reinterpret_cast<Shape::FuncPtr>(Shape::defaultCopy<LineData>),
reinterpret_cast<Shape::FuncPtr>(Shape::defaultDestruct<LineData>),
reinterpret_cast<Shape::FuncPtr>(Shape::defaultCompare<LineData>),
reinterpret_cast<Shape::FuncPtr>(Line::lineDraw),
reinterpret_cast<Shape::FuncPtr>(Line::lineDebug),
};
class ThickLine : public Line
{
protected:
struct ThickLineData
{
LineData lineData;
int width;
ThickLineData() { }
ThickLineData(Point p0, Point p1, int width)
: lineData{ p0, p1 }, width(width) { }
ThickLineData(LineData data, int width)
: lineData(data), width(width) { }
bool operator==(const ThickLineData& rhs) const
{
return this->lineData == rhs.lineData
&& this->width == rhs.width;
}
bool operator!=(const ThickLineData& rhs) const
{
return !(*this == rhs);
}
};
public:
ThickLine()
: Line(thickLineVtable)
{
data.construct<ThickLineData>();
}
ThickLine(Point p0, Point p1, int width)
: Line(thickLineVtable)
{
data.construct<ThickLineData>(p0, p1, width);
}
ThickLine(const ThickLine&) = default;
ThickLine& operator=(const ThickLine&) = default;
ThickLine(ThickLine&&) = default;
ThickLine& operator=(ThickLine&&) = default;
~ThickLine() = default;
private:
static const FuncPtr thickLineVtable[funcIndexTotalLine];
static ShapeData& accessData(Shape* shape)
{
return static_cast<ThickLine*>(shape)->data;
}
static const ShapeData& accessData(const Shape* shape)
{
return accessData(const_cast<Shape*>(shape));
}
static void thickLineDraw(const Shape* line)
{
auto& data = static_cast<const ThickLine*>(line)->data.access<ThickLineData>();
std::cout << "Drawing a thick line: " << data.lineData.endpoint[0] << "; "
<< data.lineData.endpoint[1] << "; " << data.width << std::endl;
}
static void thickLineDebug(const Line* line)
{
std::cout << "ThickLine debug:\n\t";
thickLineDraw(line);
}
};
const Shape::FuncPtr ThickLine::thickLineVtable[] =
{
reinterpret_cast<Shape::FuncPtr>(Shape::defaultCopy<ThickLineData>),
reinterpret_cast<Shape::FuncPtr>(Shape::defaultDestruct<ThickLineData>),
reinterpret_cast<Shape::FuncPtr>(Shape::defaultCompare<ThickLineData>),
reinterpret_cast<Shape::FuncPtr>(ThickLine::thickLineDraw),
reinterpret_cast<Shape::FuncPtr>(ThickLine::thickLineDebug),
};
在非抽象類(lèi)Line中加入數(shù)據(jù)比想象中困難。Line的構(gòu)造函數(shù)會(huì)把SBO數(shù)據(jù)段作為LineData來(lái)構(gòu)造,但是ThickLine需要的是ThickLineData,在LineData上再次構(gòu)造ThickLine是不安全的,因此我仿照Shape給Line加上一個(gè)protected構(gòu)造函數(shù),并把LineData開(kāi)放給ThickLine,定義ThickLineData,其中包含LineData。
這個(gè)例子說(shuō)明,值多態(tài)不只適用于一群派生類(lèi)直接繼承一個(gè)抽象基類(lèi)的情況,可以擴(kuò)展到任何單繼承的繼承鏈/樹(shù),包括繼承抽象類(lèi)與非抽象類(lèi),其中后者稍微麻煩一些,需要基類(lèi)把數(shù)據(jù)類(lèi)型開(kāi)放給派生類(lèi),讓派生類(lèi)將基類(lèi)數(shù)據(jù)與新增數(shù)據(jù)進(jìn)行組合。這一定程度上破壞了基類(lèi)的封裝性,解決辦法是把方法定義在數(shù)據(jù)類(lèi)型中,讓值多態(tài)類(lèi)起適配器的作用。
單繼承并不能概括所有“is-a”的關(guān)系,有時(shí)多重繼承和虛繼承是必要的,值多態(tài)能否支持呢?答曰:不可能,因?yàn)槎嗬^承下的派生類(lèi)的實(shí)例的大小大于任何一個(gè)基類(lèi),這與值多態(tài)要求基類(lèi)與派生類(lèi)內(nèi)存布局一致相矛盾。這應(yīng)該是值多態(tài)最明顯的局限性了吧。
模式
沒(méi)有強(qiáng)制子類(lèi)不定義數(shù)據(jù)成員的手段帶來(lái)潛在的安全問(wèn)題,編譯器自動(dòng)調(diào)用基類(lèi)拷貝函數(shù)使靜態(tài)決議不再可能,派生類(lèi)甚至還要破壞基類(lèi)數(shù)據(jù)的封裝性,這些問(wèn)題有沒(méi)有解決方案呢?在C語(yǔ)言中,類(lèi)似的問(wèn)題被Cfront編譯器解決,很容易想到值多態(tài)是否可以成為一種編程語(yǔ)言的默認(rèn)多態(tài)行為。我認(rèn)為是可以的,它尤其適合比較小的設(shè)備,但是有些問(wèn)題需要考慮。
剛剛證明了單繼承可行而多繼承不可行,這種編程語(yǔ)言只能允許單繼承。那么介于單繼承和多繼承之間的,去除了數(shù)據(jù)成員的累贅的多繼承,類(lèi)似于Java和C#中的interface,是否可行呢?我沒(méi)有細(xì)想,隱隱約約感覺(jué)是有解決方案的。
基類(lèi)中預(yù)留多少數(shù)據(jù)空間?如果由程序員來(lái)決定,程序員胡亂寫(xiě)個(gè)數(shù)字,單片機(jī)有8、16、32位的,這樣做使代碼可移植性降低?;蛘哂删幾g器來(lái)決定,比如要使50%的子類(lèi)數(shù)據(jù)可以放在本地。這看起來(lái)很和諧,但是思考一下你會(huì)發(fā)現(xiàn)它對(duì)鏈接器不友好。更糟糕的是,如果有這樣的定義:
class A { };
class B { };
class A1 : public A { B b; };
class B1 : public B { A a; };
要決定A的大小,就得先決定B的;要決定B的大小,還得先決定A的……嗯,可以出一道算法題了。
想那么多干什么,說(shuō)得好像我學(xué)過(guò)編譯原理似的。
次于語(yǔ)法,值多態(tài)是否可以一般化,寫(xiě)成一個(gè)通用的庫(kù)?polymorphic_value是一個(gè)現(xiàn)成但不完美的答案,它的主要問(wèn)題在于不能通過(guò)polymorphic_value<D>實(shí)例直接構(gòu)造polymorphic_value<B>實(shí)例(其中D是B的派生類(lèi)),這會(huì)導(dǎo)致極端情況下調(diào)用一個(gè)方法的時(shí)間復(fù)雜度為\(O(h)\)(其中\(zhòng)(h\)為繼承鏈的長(zhǎng)度)。還有一個(gè)小細(xì)節(jié)是裸的值多態(tài)永遠(yuǎn)勝于任何類(lèi)庫(kù)的:可以直接寫(xiě)shape.draw()而無(wú)需shape->draw(),后者形如指針的語(yǔ)義有一些誤導(dǎo)性。不過(guò)polymorphic_value支持多繼承與虛繼承,這是值多態(tài)永遠(yuǎn)比不上的。
我苦思冥想了很久,覺(jué)得就算C++究極進(jìn)化成了C++++也不可能存在一個(gè)類(lèi)模板能對(duì)值多態(tài)類(lèi)的設(shè)計(jì)有什么幫助,唯有退而求其次地用宏。Shape一家可以簡(jiǎn)化成這樣:
class Shape
{
VP_BASE(Shape, 16, 1);
static constexpr std::size_t funcIndexDraw = 0;
public:
void draw() const
{
if (vtable)
VP_BASE_VFUNCTION(void(*)(const Shape*), funcIndexDraw)(this);
}
};
VP_BASE_SWAP(Shape);
class Line : public Shape
{
VP_DERIVED(Line);
private:
struct LineData
{
Point endpoint[2];
LineData() { }
LineData(Point p0, Point p1)
: endpoint{ p0, p1 } { }
bool operator==(const LineData& rhs) const
{
return this->endpoint[0] == rhs.endpoint[0]
&& this->endpoint[1] == rhs.endpoint[1];
}
bool operator!=(const LineData& rhs) const
{
return !(*this == rhs);
}
};
public:
Line()
: VP_DERIVED_INITIALIZE(Shape, Line)
{
VP_DERIVED_CONSTRUCT(LineData);
}
Line(Point p0, Point p1)
: VP_DERIVED_INITIALIZE(Shape, Line)
{
VP_DERIVED_CONSTRUCT(LineData, p0, p1);
}
private:
static void lineDraw(const Shape* line)
{
auto& data = VP_DERIVED_ACCESS(const Line, LineData, line);
std::cout << "Drawing a line: " << data.endpoint[0] << "; "
<< data.endpoint[1] << std::endl;
}
};
VP_DERIVED_VTABLE(Line, LineData,
VP_DERIVED_VFUNCTION(Line, lineDraw),
);
class Rectangle : public Shape
{
VP_DERIVED(Rectangle);
private:
struct RectangleData
{
Point vertex[2];
bool filled;
RectangleData() { }
RectangleData(Point v0, Point v1, bool filled)
: vertex{ v0, v1 }, filled(filled) { }
bool operator==(const RectangleData& rhs) const
{
return this->vertex[0] == rhs.vertex[0]
&& this->vertex[1] == rhs.vertex[1]
&& this->filled == rhs.filled;
}
bool operator!=(const RectangleData& rhs) const
{
return !(*this == rhs);
}
};
public:
Rectangle()
: VP_DERIVED_INITIALIZE(Shape, Rectangle)
{
VP_DERIVED_CONSTRUCT(RectangleData);
}
Rectangle(Point v0, Point v1, bool filled)
: VP_DERIVED_INITIALIZE(Shape, Rectangle)
{
VP_DERIVED_CONSTRUCT(RectangleData, v0, v1, filled);
}
private:
static void rectangleDraw(const Shape* rect)
{
auto& data = VP_DERIVED_ACCESS(const Rectangle, RectangleData, rect);
std::cout << "Drawing a rectangle: " << data.vertex[0] << "; "
<< data.vertex[1] << "; " << (data.filled ? "filled" : "blank")
<< std::endl;
}
};
VP_DERIVED_VTABLE(Rectangle, RectangleData,
VP_DERIVED_VFUNCTION(Rectangle, rectangleDraw),
);
效果一般,并沒(méi)有簡(jiǎn)化很多。不僅如此,如果不想讓自己的值多態(tài)類(lèi)支持operator==的話(huà),還得寫(xiě)一個(gè)新的宏,非常死板。
再次于工具,值多態(tài)是否可以成為一種設(shè)計(jì)模式呢?我認(rèn)為它具有成為設(shè)計(jì)模式的潛質(zhì),因?yàn)楦鱾€(gè)值多態(tài)類(lèi)都具有相似的內(nèi)存布局,可以把共用代碼抽離出來(lái)寫(xiě)成宏。但是,由于我沒(méi)有在任何地方看到過(guò)這種用法,現(xiàn)在還不能大張旗鼓地把它作為一種設(shè)計(jì)模式來(lái)宣揚(yáng)。Anyway,讓值多態(tài)成為一種設(shè)計(jì)模式是我的愿景。(誰(shuí)還不想搞一點(diǎn)發(fā)明創(chuàng)造呢?)
比較
值多態(tài)處于傳統(tǒng)多態(tài)與類(lèi)型擦除之間,與C++中現(xiàn)有的各種多態(tài)實(shí)現(xiàn)方式相比,在它的適用范圍內(nèi),具有集大成的優(yōu)勢(shì)。
與傳統(tǒng)多態(tài)相比,值多態(tài)保留了繼承的工具與思維方式,但是與傳統(tǒng)多態(tài)的指針語(yǔ)義不同,值多態(tài)是值語(yǔ)義的,多態(tài)性可以在值拷貝時(shí)被保留。值語(yǔ)義的多態(tài)的意義不僅在于帶來(lái)方便,更有消除潛在的bug——C/C++的指針被人詬病得還不夠嗎?
與類(lèi)型擦除相比,值多態(tài)同樣使用值語(yǔ)義(類(lèi)型擦除界也有引用語(yǔ)義的),但是并非duck typing而是選擇了較為傳統(tǒng)的繼承。duck typing在靜態(tài)類(lèi)型語(yǔ)言C++中處處受限:類(lèi)型擦除類(lèi)的實(shí)例可以由duck來(lái)構(gòu)造但是無(wú)法還原;類(lèi)型擦除類(lèi)有固定的affordance,如std::function要求operator(),即使用上適配器可以搞定Shape,但對(duì)于兩個(gè)多態(tài)函數(shù)的Line和ThickLine還是束手無(wú)策。繼承作為C++原生特性不存在這些問(wèn)題,更重要的是繼承是C++和很多其他語(yǔ)言的程序員所習(xí)慣的思維方式。
與polymorphic_value相比,值多態(tài)用普適性換取了運(yùn)行時(shí)的性能和實(shí)現(xiàn)上的自由——畢竟除SBOData以外的類(lèi)都是自己寫(xiě)的。在類(lèi)型轉(zhuǎn)換時(shí),polymorphic_value會(huì)套娃,而值多態(tài)不會(huì),并且能不能轉(zhuǎn)換可以由編譯器說(shuō)了算。值多態(tài)的類(lèi)型對(duì)客戶(hù)完全開(kāi)放,用不用SBO、SBO多大都可以按需控制,甚至可以人為干預(yù)向下類(lèi)型轉(zhuǎn)換。當(dāng)然,自由的代價(jià)是更長(zhǎng)的代碼。
總結(jié)
值多態(tài)是一種介于傳統(tǒng)多態(tài)與類(lèi)型擦除之間的多態(tài)實(shí)現(xiàn)方式,借鑒了值語(yǔ)義,保留了繼承,在單繼承的適用范圍內(nèi),程序和程序員都能從中受益。本文也是《深度探索C++對(duì)象模型》中“Function語(yǔ)意學(xué)”一章的最佳實(shí)踐。
換個(gè)內(nèi)存大一點(diǎn)的單片機(jī),屁事都沒(méi)有了——技術(shù)不夠,成本來(lái)湊。
參考
Polymorphism (computer science) - Wikipedia
A polymorphic value-type for C++
N3337: Working Draft, Standard for Programming Language C++
到此這篇關(guān)于C++值多態(tài)中的傳統(tǒng)多態(tài)與類(lèi)型擦除的文章就介紹到這了,更多相關(guān)c++ 值多態(tài)類(lèi)型擦除內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++ Boost Serialization庫(kù)超詳細(xì)獎(jiǎng)金額
Boost是為C++語(yǔ)言標(biāo)準(zhǔn)庫(kù)提供擴(kuò)展的一些C++程序庫(kù)的總稱(chēng)。Boost庫(kù)是一個(gè)可移植、提供源代碼的C++庫(kù),作為標(biāo)準(zhǔn)庫(kù)的后備,是C++標(biāo)準(zhǔn)化進(jìn)程的開(kāi)發(fā)引擎之一,是為C++語(yǔ)言標(biāo)準(zhǔn)庫(kù)提供擴(kuò)展的一些C++程序庫(kù)的總稱(chēng)2022-12-12
關(guān)于C語(yǔ)言位運(yùn)算的簡(jiǎn)單示例
這篇文章主要介紹了關(guān)于C語(yǔ)言位運(yùn)算的簡(jiǎn)單示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
C語(yǔ)言圖書(shū)管理系統(tǒng)實(shí)驗(yàn)
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言圖書(shū)管理系統(tǒng)實(shí)驗(yàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
使用VS Code進(jìn)行Qt開(kāi)發(fā)的實(shí)現(xiàn)
這篇文章主要介紹了使用VS Code進(jìn)行Qt開(kāi)發(fā)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
c語(yǔ)言conio.h基本知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家分享的是關(guān)于c語(yǔ)言conio.h是什么意思的相關(guān)知識(shí)點(diǎn),需要的朋友們可以學(xué)習(xí)參考下。2020-02-02
C語(yǔ)言學(xué)生學(xué)籍管理系統(tǒng)課程設(shè)計(jì)
這篇文章主要介紹了C語(yǔ)言學(xué)生學(xué)籍管理系統(tǒng)課程設(shè)計(jì),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
Qt添加MSVC2017編譯器的實(shí)現(xiàn)方法
Qt添加MSVC2017編譯器是開(kāi)發(fā)者在Windows平臺(tái)上進(jìn)行Qt應(yīng)用程序開(kāi)發(fā)的重要步驟,本文詳細(xì)介紹了如何為Qt配置MSVC2017編譯器的具體步驟,感興趣的可以了解一下2023-09-09

