惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Cisco Blogs
爱范儿
爱范儿
有赞技术团队
有赞技术团队
博客园 - 【当耐特】
Jina AI
Jina AI
Project Zero
Project Zero
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
Simon Willison's Weblog
Simon Willison's Weblog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tenable Blog
F
Fortinet All Blogs
大猫的无限游戏
大猫的无限游戏
Last Week in AI
Last Week in AI
月光博客
月光博客
雷峰网
雷峰网
G
Google Developers Blog
V
V2EX
T
Tor Project blog
罗磊的独立博客
Schneier on Security
Schneier on Security
Know Your Adversary
Know Your Adversary
W
WeLiveSecurity
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
P
Privacy International News Feed
S
Securelist
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Proofpoint News Feed
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
小众软件
小众软件
Scott Helme
Scott Helme
I
Intezer
T
Threat Research - Cisco Blogs
The GitHub Blog
The GitHub Blog
N
Netflix TechBlog - Medium
C
CERT Recently Published Vulnerability Notes
Security Archives - TechRepublic
Security Archives - TechRepublic
酷 壳 – CoolShell
酷 壳 – CoolShell
L
LINUX DO - 最新话题
N
News | PayPal Newsroom
L
Lohrmann on Cybersecurity
T
Troy Hunt's Blog
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
人人都是产品经理
人人都是产品经理
Latest news
Latest news
AWS News Blog
AWS News Blog
Apple Machine Learning Research
Apple Machine Learning Research

博客园 - 撬棍

【.Net】2、8、16进制转换 【.Net】执行CMD命令 【.Net】获取随机数函数 【.Net】注册程序开机启动 【.Net】把窗体“钉”到桌面上 【.Net】多语言查看MSDN 【.Net】 显示星期字符串 【.Net】 判断时间字符串正确性 【.Net】 实现窗口拖动 【.Net】 Winform 单例运行实例 [C++]数组参数 [C++]const的指针使用 [C++]指针类型出参 [VBA]Excel输出utf-8编码格式文件 使用WideCharToMultiByte 【C++】split [C语言学习]之打印万年历 - 撬棍 - 博客园 [VB6.0]让程序在任务列表和资源管理器“隐身” [InstallShield]FindAllFiles与SetFileInfo配合实现文件加多文件属性设置 [VB]修改注册表让程序开机自动运行 - 撬棍 - 博客园
[C++]函数返回值
撬棍 · 2013-05-23 · via 博客园 - 撬棍

1.缺省情况下函数的返回值是按值传递的passed by value 这意味着得到控制权的
函数将接收返回语句中指定的表达式的拷贝例如

Matrix grow( Matrix* p ) 
{
    Matrix val;
    // ...
    return val;
}

grow()把存储在val 中的值的拷贝返回到调用函数但调用函数不能用任何方式修改val。该缺省行为可以被改变一个函数可以被声明为返回一个指针或一个引用。

2.1返回一个指向局部对象的引用,局部对象的生命期随函数的结束而结束。

// 问题: 返回一个指向局部对象的引用
Matrix& add( Matrix &m1, Matrix &m2 )
{
    Matrix result;
    if ( m1.isZero() )
        return m2;
    if ( m2.isZero() )
        return m1;
    // 将两个Matrix 对象的内容相加
    // 喔! 返回之后结果指向一个有问题的位置
    return result;
}

在这种情况下返回类型应该被声明为非引用类型然后再在局部对象的生命期结束之前拷贝局部变量。

2.2函数返回一个左值对返回值的任何修改都将改变被返回的实际对象。

#include <vector>
int &get_val( vector<int> &vi, int ix ) 
{
    return vi[ix];
}
int ai[4] = { 0, 1, 2, 3 };
vector<int> vec( ai, ai+4 ); // 将ai 的4 个元素复制到vec
int main() 
{
    // 将 vec[0] 增加到 1
    get_val( vec,0 )++;
    // ...
}

为防止对引用返回值的无意修改返回值应该被声明为const:

问题:你知道下列函数定义有什么潜在的运行问题吗

vector<string> &readText( ) 
{
    vector<string> text;
    string word;
    while ( cin >> word ) 
    {
        text.push_back( word );
        // ...
    }
    // ....
    return text;
}

个人觉得有2个办法

1.不传引用:缺点性能低下。

2.作为输出参数传递