64,639
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class my
{
public:
char *d;
public:
char*operator()(char*s)
{
d=new char[(strlen(s)+1)];
strcpy(d,s);
cout <<"in strcpy1 " <<endl<<d <<endl;
return d;
}
~my()
{
delete [] d;
}
};
int main()
{
char *str="hello";
my strcpy1;
strcpy1(str);
cout<<strcpy1.d<<endl;
system("pause");
}
个人认为操作这种纯c风格的字串最好还是不用智能指针的好,一方面有效能的考虑,另一方面语义也并不是很直观!
直接:
char* _strcpy(char *s)
{
char* temp=new [strlen(s)+1];
char* p=temp;
.....do something.....
return p;
}
然后在设计一个:
void release(void* p)
{
delete []p;
}
在设计文档中说明调用_strcpy进行字串拷贝,release函数释放资源
或干脆把这两种行为封装在一个类中
#include<iostream>
#include<string>
#include <memory>
using namespace std;
class _strcpy
{
public:
_strcpy(char *s)
{
char* temp=new char[strlen(s)+1];
ele=temp;
while((*temp++=*s++)!='\0');
}
~_strcpy()
{
delete []ele;
}
operator char*()
{
return ele;
}
private:
_strcpy(const _strcpy& rhs) //暂时没考虑对象拷贝、赋值的问题
{
}
_strcpy& operator=(const _strcpy& rhs)
{
return *this;
}
char* ele;
};
int main(void)
{
char s[]="HEllo";
cout<<_strcpy(s);
system("pause");
return 0;
}
#include <iostream>
#include <memory>
using namespace std;
auto_ptr <char*> &strcpy1(char *s) //这个地方要用引用,否则返回值拷贝的时候,把里面的对象析构了。
{
char *d=new char[(strlen(s)+1)];
char *m=d;
while((*d++=*s++)!='\0');
auto_ptr <char*> *ptr=new auto_ptr<char*>(m);//这个得自己new一个出来,不然出了函数的范围,又析构了。
cout <<"in strcpy1 " <<m <<endl;
return *ptr;
}
int main(void)
{
char s[]="HEllo";
char **d;
d=strcpy1(s).get();//这里有个毛病,就是本身这个auto_ptr<char*>,这块内存没法删除了。
system("pause");
return 0;
}