gpt4 book ai didi

c++ - C++ 中的写时复制指针对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:27:58 25 4
gpt4 key购买 nike

我试着关注这篇文章 http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-on-write关于如何在 C++ 中实现写指针复制。问题是,它对我不起作用。

该对象的症结在于重载取消引用运算符 (*) 以在它应该返回非常量引用时进行后台复制:

   const T& operator*() const
{
return *m_sp;
}
T& operator*()
{
detach();
return *m_sp;
}

遗憾的是,似乎只有第二个版本运行过。C-outing 我指向的对象创建一个拷贝,甚至做类似的事情

   CowPtr<string> my_cow_ptr(new string("hello world"));
const string& const_ref=*my_cow_ptr;

导致 detach() 函数运行。

关于为什么它没有像宣传的那样工作有什么想法吗?

最佳答案

const 成员函数将在 const 对象上调用。所以:

const CowPtr<std::string> my_const_cow_ptr(new std::string("Hello, world"));
const std::string& str = *my_const_cow_ptr;

CowPtr<std::string> my_cow_ptr(new std::string("Hello, world"));
const std::string& str = *static_cast<const CowPtr<std::string>&>(my_cow_ptr);

关于c++ - C++ 中的写时复制指针对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16123676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com