对象切片:派生类塞进基类容器时丢了什么
你写了一个基类 Shape,派生类 Circle 重写了虚函数,本地测试一切正常。可一旦把对象放进 std::vector<Shape>,或者传给一个按值接收 Shape 的函数,多态就像失灵了一样:调用的是基类版本,派生类新增的数据也不见了。
程序没有崩溃,没有警告,甚至能编译通过。这种问题叫对象切片(object slicing)。它不神秘,但很容易在“把对象存起来”或“把对象传出去”的时候悄悄发生。
一个能编译、能运行,但结果不对的例子
先看一段完整代码:
1// slice.cpp
2#include <iostream>
3#include <string>
4#include <vector>
5
6struct Shape {
7 std::string name = "shape";
8
9 virtual std::string kind() const {
10 return "Shape";
11 }
12
13 virtual ~Shape() = default;
14};
15
16struct Circle : Shape {
17 double radius;
18
19 explicit Circle(double r) : radius(r) {
20 name = "circle";
21 }
22
23 std::string kind() const override {
24 return "Circle(r=" + std::to_string(radius) + ")";
25 }
26};
27
28void printKind(Shape s) {
29 std::cout << "printKind: " << s.kind() << ", name=" << s.name << "\n";
30}
31
32int main() {
33 Circle c(2.5);
34
35 printKind(c);
36
37 std::vector<Shape> shapes;
38 shapes.push_back(c);
39 std::cout << "vector: " << shapes[0].kind() << ", name=" << shapes[0].name << "\n";
40
41 Shape s = c;
42 std::cout << "copy: " << s.kind() << ", name=" << s.name << "\n";
43}编译运行:
1g++ -std=c++17 -Wall -Wextra -pedantic slice.cpp -o slice
2./slice输出:
1printKind: Shape, name=circle
2vector: Shape, name=circle
3copy: Shape, name=circle这里有两个细节值得注意:
name是Shape的成员,它被复制了,所以还是circle。kind()是虚函数,但调用结果变成了Shape;Circle::radius更是连存放的位置都没有。
这就是切片:派生类对象被“塞进”一个基类对象时,只有基类子对象那一部分被保留下来。
切片发生了什么
可以把对象的内存粗略理解成这样:
1Circle c:
2+-------------------+---------+
3| Shape subobject | radius |
4+-------------------+---------+
5
6拷贝或赋值给 Shape 对象后:
7
8Shape s:
9+-------------------+
10| Shape subobject |
11+-------------------+Circle 比 Shape 多出来的数据(这里是 radius)没有地方存放,只能被丢弃。与此同时,s 是一个真正的 Shape 对象,它的动态类型就是 Shape,虚函数调用自然会解析到 Shape::kind()。
这不是编译器“偷懒”,而是 C++ 值语义的直接结果:Shape 类型的变量只能容纳一个 Shape 大小、Shape 布局的对象。
三种常见的切片场景
1. 函数按值接收基类
1void printKind(Shape s); // s 是一个新的 Shape 对象调用 printKind(c) 时,参数 s 会用 c 的 Shape 子对象进行拷贝构造。函数内部看到的永远是 Shape。
如果函数只是读取对象,应该改成引用:
1void printKind(const Shape& s) {
2 std::cout << s.kind() << "\n";
3}需要修改对象时用 Shape&,不希望传空值时引用通常比指针更明确。
2. 把派生类放进基类值容器
1std::vector<Shape> shapes;
2shapes.push_back(Circle(2.5));vector<Shape> 的每个元素都是 Shape 对象,容量、步长、拷贝方式都按 Shape 计算。放进去的 Circle 会被切成 Shape。
这类代码最危险的地方在于:它看起来很自然,尤其是从 Java、C# 等“对象默认是引用”的语言转过来时。
3. 赋值给基类对象
1Circle c(2.5);
2Shape s;
3s = c; // 用 Circle 的 Shape 部分赋值拷贝初始化 Shape s = c; 和赋值 s = c; 都可能发生切片。区别只是调用拷贝构造还是拷贝赋值运算符,结果都是派生部分丢失。
怎么正确保存多态对象
核心原则很简单:需要多态时,不要存“基类值”,要存“指向对象的句柄”。
| 方式 | 会切片吗 | 谁拥有对象 | 适用场景 | 注意事项 |
|---|---|---|---|---|
std::vector<Shape> | 会 | 容器拥有值对象 | 只有基类本身、没有继承需求 | 多态层次不要用 |
const Shape& 参数 | 不会 | 调用方拥有 | 函数只观察对象 | 引用对象必须仍然有效 |
std::vector<std::unique_ptr<Shape>> | 不会 | 容器独占拥有 | 容器管理对象生命周期 | 容器不能隐式拷贝 |
std::vector<std::shared_ptr<Shape>> | 不会 | 多方共享拥有 | 多处共享同一对象 | 有引用计数开销,注意循环引用 |
std::vector<std::reference_wrapper<Shape>> | 不会 | 外部拥有 | 临时借用一组已存在对象 | 对象生命周期必须长于容器 |
容器独占所有权:unique_ptr
大多数情况下,这是多态容器的默认选择。
1#include <iostream>
2#include <memory>
3#include <string>
4#include <vector>
5
6struct Shape {
7 virtual ~Shape() = default;
8 virtual std::string kind() const { return "Shape"; }
9};
10
11struct Circle : Shape {
12 double radius;
13 explicit Circle(double r) : radius(r) {}
14
15 std::string kind() const override {
16 return "Circle(r=" + std::to_string(radius) + ")";
17 }
18};
19
20int main() {
21 std::vector<std::unique_ptr<Shape>> shapes;
22 shapes.push_back(std::make_unique<Circle>(2.5));
23 shapes.push_back(std::make_unique<Shape>());
24
25 for (const auto& p : shapes) {
26 std::cout << p->kind() << "\n";
27 }
28}输出:
1Circle(r=2.500000)
2Shape这里容器存的是指针,对象本身在堆上独立存在,不会被切片。unique_ptr 也清楚表达了所有权:容器被销毁时,里面的对象也一起销毁。
临时借用:reference_wrapper
如果对象已经由别处管理,你只是想把它们放在一起处理,可以存引用包装:
1#include <functional>
2#include <iostream>
3#include <vector>
4
5struct Shape {
6 virtual ~Shape() = default;
7 virtual std::string kind() const { return "Shape"; }
8};
9
10struct Circle : Shape {
11 std::string kind() const override { return "Circle"; }
12};
13
14int main() {
15 Circle c;
16 Shape s;
17
18 std::vector<std::reference_wrapper<Shape>> shapes;
19 shapes.push_back(c);
20 shapes.push_back(s);
21
22 for (Shape& item : shapes) {
23 std::cout << item.kind() << "\n";
24 }
25}这不会切片,但有一个硬要求:c 和 s 的生命周期必须覆盖 shapes 的使用期。引用不延长生命周期,悬空引用比切片更难排查。
需要值语义:clone
有时你确实想要“复制一份多态对象”,比如复制一个图形列表。unique_ptr 不能隐式拷贝,这时可以给基类加一个 clone() 接口:
1#include <iostream>
2#include <memory>
3#include <string>
4#include <vector>
5
6struct Shape {
7 virtual ~Shape() = default;
8 virtual std::unique_ptr<Shape> clone() const = 0;
9 virtual std::string kind() const = 0;
10};
11
12struct Circle : Shape {
13 double radius;
14 explicit Circle(double r) : radius(r) {}
15
16 std::unique_ptr<Shape> clone() const override {
17 return std::make_unique<Circle>(*this);
18 }
19
20 std::string kind() const override {
21 return "Circle(r=" + std::to_string(radius) + ")";
22 }
23};
24
25int main() {
26 std::vector<std::unique_ptr<Shape>> original;
27 original.push_back(std::make_unique<Circle>(2.5));
28
29 std::vector<std::unique_ptr<Shape>> copied;
30 copied.reserve(original.size());
31 for (const auto& p : original) {
32 copied.push_back(p->clone());
33 }
34
35 std::cout << copied[0]->kind() << "\n";
36}clone() 返回的是派生类的完整副本,外部通过基类指针持有。这样既保留了多态,又有了明确的复制语义。
让编译器提前报错
如果一个基类本来就是为多态设计的,允许它被拷贝往往没有意义,还会留下切片隐患。可以主动删除拷贝操作:
1struct Shape {
2 Shape() = default;
3 virtual ~Shape() = default;
4
5 Shape(const Shape&) = delete;
6 Shape& operator=(const Shape&) = delete;
7};这样写之后,Shape s = c;、std::vector<Shape>、按值传参等切片路径会直接编译失败。错误提前到编译期,比运行时少掉一半虚函数行为要好得多。
这条规则不是绝对的。删除拷贝意味着对象不能按值复制;如果你需要复制,就配合 clone() 提供显式的深拷贝。关键是不要让“看起来能复制、实际会切片”的默认行为留在接口里。
排查时可以问自己的三个问题
遇到“虚函数没按预期调用”的情况,除了检查虚函数声明和对象实际类型,还可以快速排查切片:
- 对象有没有被按值传递? 函数参数、lambda 捕获、返回值都可能发生。
- 容器存的是值还是句柄?
vector<Base>和vector<unique_ptr<Base>>是完全不同的语义。 - 有没有把派生类赋给基类对象? 包括成员变量、局部变量和旧式数组。
小结
对象切片的本质不是“多态坏了”,而是你把一个多态对象降级成了基类值对象。基类子对象的数据还在,但派生类独有的状态和动态行为已经被截断。
写 C++ 多态代码时,可以记住一条朴素的经验:参数尽量用引用,容器尽量存智能指针;如果基类不该被复制,就把拷贝操作删掉。把切片挡在编译期,往往比事后调试虚函数调用链省心得多。
相关文章
- 表达式里的求值顺序:同一行代码,换个编译器结果就变了
- 构造函数里调虚函数,多态为什么没生效
- C++ string_view 实战:不拷贝,也不保证活着
- C++ 迭代器失效:删掉一个元素,循环为什么漏掉一个
本文由 AI 辅助生成并经人工校验,如有疏漏欢迎指正。