一个关于引用和返回值得问题

sducs 2007-04-26 08:57:22
主要程序:
typedef pair<short,short> location;
typedef vector<location> loc;
typedef vector<string> text;
typedef pair<text*,loc*> text_loc;


text_loc* separate_words(const vector<string> *text_file)
{
vector<string> *words=new vector<string>;
vector<location> *locations=new vector<location>;
.......
return new text_loc(words,locations);
}


怎么函数返回值是text_loc*类型
而return的是new text_loc(words,locations),这是个指针吗?
...全文
165 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
longshanks 2007-04-26
  • 打赏
  • 举报
回复
可以直接返回pair<>类型,而不是pair<>*:
text_loc separate_words(const vector<string> *text_file)
{
vector<string> *words=new vector<string>;
vector<location> *locations=new vector<location>;
.......
return text_loc(words,locations);
}
这样可以省去你在函数外delete的操作。更加简便,也更不容易出错。
或许你觉得这样效率低,因为构造了一个新的对象,还进行拷贝。但是不用担心,C++标准要求对这种返回对象进行优化,不产生临时对象和对象拷贝。而现在的大多数编译器也做到了。
Benny_ywb 2007-04-26
  • 打赏
  • 举报
回复
顶下
lin_style 2007-04-26
  • 打赏
  • 举报
回复
函数名那写着嘛
text_loc*...
ytfhwfnh 2007-04-26
  • 打赏
  • 举报
回复
new得到的东西就是指针啊。这个函数利用pair返回了两个指针,tuple是不是更合适一点?
飞哥 2007-04-26
  • 打赏
  • 举报
回复
new了一个对象
返回的是首地址的指针
FingerStyle 2007-04-26
  • 打赏
  • 举报
回复
而return的是new text_loc(words,locations),这是个指针吗?

okok

返回堆的地址..

65,213

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧