【问题标题】:Initialize std::shared_ptr by copying a junk of data from a raw pointer通过从原始指针复制垃圾数据来初始化 std::shared_ptr
【发布时间】:2015-10-03 09:09:24
【问题描述】:

基本上是我希望达到的目标:

int pBuf = {1, 2, 3, 4, 5, 6};
std::shared_ptr<int> pPtr(pBuf, _ARRAYSIZE(pBuf));

以下语法无效,甚至可能吗? 我必须使用 shared_ptr。

【问题讨论】:

  • 既然您自己承认,该代码没有实现您的目标,我们无法仅通过阅读就神奇地预测您想要做什么。你必须解释你想要做什么......
  • 你想用int pBuf = {1, 2, 3, 4, 5, 6};做什么?你的意思是int pBuf[] = {1, 2, 3, 4, 5, 6};
  • @NathanOliver 你是对的,我的错
  • @LightnessRacesinOrbit,这是一个一般示例,我想在不访问任何 std::copy 或 memcpy 函数的情况下将缓冲区复制到 shared_ptr 中
  • 我不知道“将缓冲区复制到 shared_ptr”是什么意思,或者您为什么不想使用标准库功能。解释你的目标。

标签: c++ windows c++11 stl smart-pointers


【解决方案1】:

如果您要创建数组 pBuf 的副本并将其分配给 std::shared_ptr,则以下代码应该可以工作:

int pBuf[] = {1, 2, 3, 4, 5, 6};
std::shared_ptr<int> pPtr( new int[_ARRAYSIZE(pBuf)], std::default_delete<int[]>() );
std::copy( pBuf, pBuf + _ARRAYSIZE(pBuf), pPtr.get() );

【讨论】:

    猜你喜欢
    • 2012-09-07
    • 2019-11-07
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多