首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么这是按值调用的?

为什么这是按值调用的?
EN

Stack Overflow用户
提问于 2013-01-04 20:02:55
回答 1查看 166关注 0票数 0

这就是我的问题:

代码语言:javascript
复制
/**
* Example of the book:
* C++ Templates page 17/18
*/

#include <iostream>
#include <cstring>
#include <string>

// max of two values of any type (call by reference)
template <typename T>
inline T const& max (T const& a, T const& b) {
    return a < b ? b : a;
}

// max of two C-strings (call by value) 
inline char const* max (char const* a, char const* b) {
    // ??? Creates this a new temporary local value that may be returned?
    // I can't see where the temporary value is created!
    return std::strcmp(a,b) < 0 ? b : a;
}

// max of three values of any type (call by reference)
template <typename T>
inline T const& max (T const& a, T const& b, T const& c) {
    return max (max(a,b),c); // warning "error", if max(a,b) uses call-by-value
                             // warning:  reference of temp value will be returned

int main() {
    // call by reference 
    std::cout << ::max(7, 42, 68) << std::endl;

    const char* s1 = "Tim";
    const char* s2 = "Tom";
    const char* s3 = "Toni";
    // call the function with call by value
    // ??? Is this right?
    std::cout << ::max(s1,s2) << std::endl;

    std::cout << ::max(s1, s2, s3) << std::endl;
}

对于C字符串,函数max中的临时局部值在哪里?

这个函数有两个指针,那么为什么它是按值调用的呢?

对不起,我认为这是一个非常愚蠢的问题,但我不明白它。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2013-01-04 20:06:05

对于C字符串,函数max中的临时局部值在哪里?

以下内容:

代码语言:javascript
复制
return std::strcmp(a,b) < 0 ? b : a;

等同于:

代码语言:javascript
复制
const char *ret = std::strcmp(a,b) < 0 ? b : a;
return ret;

我希望所讨论的“临时本地值”是未命名的ret等价物。

函数有两个指针,那么为什么它是按值调用的呢?

每个C字符串都由const char*表示,而const char*是通过值传递的。这意味着,如果函数要修改ab (即指针本身),调用者将看不到修改。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14156848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档