vs2008关于C++的shared_ptr

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vs2008关于C++的shared_ptr相关的知识,希望对你有一定的参考价值。

一直显示有错误,说我未声明,这个不是在memory这个头文件里自动声明的吗
#include<iostream>
#include<string>
#include<memory>

using namespace std;
int main()

auto_ptr<string> file[5]=

auto_ptr<string> (new string("chai liqing")),
auto_ptr<string> (new string("zhang liang")),
auto_ptr<string> (new string("zou luting")),
auto_ptr<string> (new string("cai nanhe")),
auto_ptr<string> (new string("lu nongnong"))
;
shared_ptr<string> xuanze;
xuanze=file[1];
cout<<"*****全部打印*****"<<endl;
for(int i=0;i<5;i++)
cout<<"file["<<i<<"]="<<*file[i]<<endl;
cout<<"*****打印一个*****"<<endl;
cout<<"xuanze="<<*xuanze<<endl;
getchar();
return 0;

shared_ptr需要VS2008 SP1以上才自带有,头文件为#include <memory>,或者使用boost库(boost::shared_ptr),头文件为#include <boost/shared_ptr.hpp>

vs2008 error C2039: “shared_ptr”: 不是“std::tr1”的成员

vs2008创建的c++项目中用到了std::tr1::shared_ptr,
编译时报错:error C2039: “shared_ptr”: 不是“std::tr1”的成员。
原因:未安装vs2008 SP1
VS90sp1-KB945140-CHS.exe:
http://www.microsoft.com/downloads/zh-cn/details.aspx?FamilyID=FBEE1648-7106-44A7-9649-6D9F6D58056E
VS2008SP1CHSX1512981.iso:
http://www.microsoft.com/downloads/zh-cn/details.aspx?FamilyID=27673C47-B3B5-4C67-BD99-84E525B5CE61
若 不安装vs2008 SP1,也可使用Boost的实现boost::shared_ptr
参考技术A 我vs2010通过编译了,2008貌似没有实现 参考技术B 你的头文件去哪里了?

C++ auto_ptr 和 shared_ptr 从 VC++10 更改为 VC++12

【中文标题】C++ auto_ptr 和 shared_ptr 从 VC++10 更改为 VC++12【英文标题】:C++ auto_ptr and shared_ptr changes from VC++10 to VC++12 【发布时间】:2014-06-12 13:50:57 【问题描述】:

我正在努力将代码库从 Visual Studio 和 C++10 更新到 VS/C++12

我遇到了一个与 shared_ptr 和 auto_ptr 相关的症结。

原来C++10中的代码是

void CommandLoader::RegisterCommand(std::auto_ptr<ILoadableCommand> cmd)

assert(cmd.get() != NULL);
m_pImpl->m_registered.push_back(shared_ptr<ILoadableCommand>(cmd));

编译错误是:

error C2440: '<function-style-cast>' : cannot convert from std::auto_ptr<ILoadableCommand>' to 'std::shared_ptr<ILoadableCommand>'

在编辑器内部,它抱怨说

Error: no instance of constructor"std::shared_ptr<_Ty> matches the argument list.

我的猜测是 auto_ptr 不再被接受为 shared_ptr 构造函数的参数,但http://msdn.microsoft.com/en-us/library/bb981959.aspx 另有说法。

我有点茫然,所以任何帮助都会很棒!

【问题讨论】:

你可能也应该使用 nullptr,顺便说一句。 shared_ptr&lt;ILoadableCommand&gt;(std::move(cmd)). 谢谢简单。似乎现在可以工作了! 还有一件事,将auto_ptr 更改为unique_ptr,因为auto_ptr 存在严重缺陷并且已被弃用。 【参考方案1】:

简而言之:不要使用 auto_ptr。基本上已经坏掉了。请改用 std::unique_ptr。

你使用 auto_ptr 的方式也很奇怪:

void CommandLoader::RegisterCommand(std::auto_ptr<ILoadableCommand> cmd)

这意味着每次调用此函数时,它都会创建一个新的 auto_ptr 来获取缓冲区的所有权。然后,您将其所有权授予 shared_ptr。

这听起来像是你应该给函数一个原始指针的情况,或者至少是一个引用:

void CommandLoader::RegisterCommand(std::unique_ptr<ILoadableCommand>& cmd)

MSDN Magazine article 也涵盖了这一点。

【讨论】:

以上是关于vs2008关于C++的shared_ptr的主要内容,如果未能解决你的问题,请参考以下文章

挣扎 - 又一个内存损坏问题,错误分配(C++,VS 2008)

将托管 C++ 从 vs2003 移植到 vs2008 的问题

在将大型 C++ 程序从 VS2005 转换为 VS2008 之前我应该​​知道啥?

如何将 vs2008 c++ OpenCV dll 构建到 vs2008 C#?

VS2008 中的 C++ 项目有效,但在 VS2010 中无效

弄清楚是啥让 VS2008 中的 C++ 类抽象