問題描述
我有一個棘手的情況.它的簡化形式是這樣的
I have a tricky situation. Its simplified form is something like this
class Instruction
{
public:
virtual void execute() { }
};
class Add: public Instruction
{
private:
int a;
int b;
int c;
public:
Add(int x, int y, int z) {a=x;b=y;c=z;}
void execute() { a = b + c; }
};
然后在一節課中我做了一些類似的事情......
And then in one class I do something like...
void some_method()
{
vector<Instruction> v;
Instruction* i = new Add(1,2,3)
v.push_back(*i);
}
在另一個班級...
void some_other_method()
{
Instruction ins = v.back();
ins.execute();
}
他們以某種方式共享這個指令向量.我關心的是我執行執行"功能的部分.它會起作用嗎?它會保留其 Add 類型嗎?
And they share this Instruction vector somehow. My concern is the part where I do "execute" function. Will it work? Will it retain its Add type?
推薦答案
不,不會.
vector<Instruction> ins;
存儲值,而不是引用.這意味著,無論你如何處理,除了那里的那個 Instruction 對象,它會在未來的某個時候被復制.
stores values, not references. This means that no matter how you but that Instruction object in there, it'll be copied at some point in the future.
此外,由于您使用 new
進行分配,因此上述代碼會泄漏該對象.如果你想正確地做到這一點,你必須這樣做
Furthermore, since you're allocating with new
, the above code leaks that object. If you want to do this properly, you'll have to do
vector<Instruction*> ins
或者,更好:
vector< std::reference_wrapper<Instruction> > ins
我喜歡這個這篇博文來解釋reference_wrapper
這種行為稱為對象切片.
這篇關于C++ 中的向量和多態性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!