You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何不使用布尔参数实现深、浅拷贝构造函数?

解决方案

下面提供两种工业界常用的优化方案,完全规避布尔参数的可读性问题:

方案1:标签分发实现显式语义的构造函数

通过定义无状态的空标签类型区分不同拷贝语义的构造函数,调用时语义明确:

class A {
public:
    // 拷贝语义标签,对外公开
    struct DeepCopyTag {};
    struct ShallowCopyTag {};

    // 对应语义的拷贝构造函数
    A(const A& other, DeepCopyTag) : small(other.small), big(std::make_shared<B>(*other.big)) {}
    A(const A& other, ShallowCopyTag) : small(other.small), big(other.big) {}

    // 其余原有构造函数...
private:
    int small;
    std::shared_ptr<B> big;
};

调用示例:

A origin(...); // 原始对象
A deep_copy(origin, A::DeepCopyTag{}); // 显式深拷贝
A shallow_copy(origin, A::ShallowCopyTag{}); // 显式浅拷贝

方案2:静态工厂方法(更推荐)

把拷贝构造函数设为私有,通过命名清晰的静态方法创建拷贝,完全避免误用:

class A {
public:
    // 原有公开构造函数,用于创建原始A对象
    A(int small_val, std::shared_ptr<B> big_ptr) : small(small_val), big(std::move(big_ptr)) {}

    // 公开的静态工厂方法,语义一目了然
    static A makeDeepCopy(const A& other) {
        return A(other, DeepCopyTag{});
    }
    static A makeShallowCopy(const A& other) {
        return A(other, ShallowCopyTag{});
    }

private:
    int small;
    std::shared_ptr<B> big;

    // 私有标签和拷贝构造函数,仅内部使用
    struct DeepCopyTag {};
    struct ShallowCopyTag {};
    A(const A& other, DeepCopyTag) : small(other.small), big(std::make_shared<B>(*other.big)) {}
    A(const A& other, ShallowCopyTag) : small(other.small), big(other.big) {}
};

调用示例:

A origin(...);
A deep_copy = A::makeDeepCopy(origin);
A shallow_copy = A::makeShallowCopy(origin);

额外建议

如果浅拷贝场景下确定不会修改A::big指向的内容,建议将std::shared_ptr<B>改为std::shared_ptr<const B>,编译器会主动禁止对共享B对象的修改,避免意外改动导致的隐蔽bug。

内容的提问来源于stack exchange,提问作者mwhite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:45:03