相关疑难解决方法(0)

为什么返回类型的类型限定符毫无意义?

说我有这个例子:

char const * const
foo( ){
   /* which is initialized to const char * const */
   return str;
}
Run Code Online (Sandbox Code Playgroud)

正确的方法是什么来避免编译器警告"返回类型的类型限定符是没有意义的"?

c c++

21
推荐指数
2
解决办法
2万
查看次数

理解“顶层的‘const’,这可能会降低代码的可读性,而不会提高 const 的正确性”

请考虑下面的代码,特别是观察get_length返回const size_t.

#include <stdio.h>

const size_t get_length(void)
{
    return 123;
}

void foo(void)
{
    size_t length = get_length();
    length++;
    
    printf("Length #1 is %zu\n", length);
}

void bar(void)
{
    // Still 123 because length was copied from get_length
    // (copy ellision notwithstanding, which is not the point here)
    size_t length = get_length();
    
    printf("Length #2 is %zu\n", length);
}

int main(void) {
    foo();
    bar();
}
Run Code Online (Sandbox Code Playgroud)

输出:

Length #1 is 124
Length #2 is 123
Run Code Online (Sandbox Code Playgroud)

我从 clang-tidy 收到以下警告:

Clang-Tidy: …
Run Code Online (Sandbox Code Playgroud)

c const-correctness clang-tidy

6
推荐指数
1
解决办法
5711
查看次数

在C++ 11中返回const值类型对移动语义的影响

我不清楚返回const值对C++ 11中移动语义的影响.

这两个返回数据成员的函数有什么区别吗?const在C++ 11中仍然是多余的?

int GetValueA() { return mValueA; }
const int GetValueB() { return mValueB; }
Run Code Online (Sandbox Code Playgroud)

这些功能怎么样?

int GetValuesAB() { return mValueA + mValueB; }
const int GetValuesCD() { return mValueC + mValueD; }
Run Code Online (Sandbox Code Playgroud)

c++ const move-semantics c++11

3
推荐指数
1
解决办法
917
查看次数

返回const值的函数

可能重复:
为了清楚起见,是否应使用返回类型的无用类型限定符?

我很困惑,按值返回并返回一个const值.例如,在功能完成后的任何功能中,所有本地人都超出范围.因此,如果我从函数返回一个值,它必须是一个副本传递,除非它通过引用返回.因此,当发生这种情况时,该函数返回一个可以在以后修改的副本.因此,即使局部变量被声明为const,我也可以在另一个变量中读取它并轻松修改后者.

const int DoubleValue(int nX)
{
    int nValue = nX * 2;
    return nValue; // A copy of nValue will be returned here
} // n
Run Code Online (Sandbox Code Playgroud)

我很困惑,想弄清楚const这里的意思.是nValueconst的函数体?如果我做了一个分配,就像在z = DoubleValue(x);,我可以明显地修改z.

在什么情况下执行常量?对象DoubleValue(x)是const对象吗?它代表什么?

c++ const return

2
推荐指数
1
解决办法
3186
查看次数

C++中的const混淆

可能重复:
为什么我的返回类型无意义?

嗨,我对特定的const转换感到困惑.我有类似的东西

// Returns a pointer that cannot be modified,   
// although the value it points to can be modified.  
double* const foo()  
{  
    static double bar = 3.14;  
    return &bar;  
}

int main()  
{  
    double* const x = foo(); // fine  
    const double* y = foo(); // eh?!  
    return 0;  
}
Run Code Online (Sandbox Code Playgroud)

当我在MSVS 2008(Express)上编译它时没有错误,但在我看来应该有.x和y背后的含义是完全不同的,所以似乎不应该有这种隐式转换.这是编译器的问题(不太可能),或者我对这里涉及的常量的理解(很可能).

c++ compiler-construction pointers const

1
推荐指数
1
解决办法
404
查看次数