Const被烘焙到客户端代码中.Readonly不是.但const速度更快.可能只是略有一点.
现在的问题是,是否有过,你应该喜欢的任何场景const过readonly?或者换言之,我们实际上并不总是更好地使用readonly而不是const(记住上述烘焙的东西)?
在C++标准库中,该值std::numeric_limits<T>::max()被指定为函数.特定类型的其他属性以常量(如std::numeric_limits<T>::is_signed)给出.所有类型的常量都是T作为函数给出的,而所有其他常量都是以常量值的形式给出的.
这背后的理由是什么?
我的项目只包含两个源文件:
a.cpp:
const int n = 8;
Run Code Online (Sandbox Code Playgroud)
b.cpp:
extern const int n;
int main()
{
// error LNK2001: unresolved external symbol "int const n" (?n@@3HB)
int m = n;
}
Run Code Online (Sandbox Code Playgroud)
我知道有几种方法可以使它工作; 但是,我只是想知道为什么它不起作用?
假设我有一个类需要一些常量来运行.几个成员函数需要使用这些常量.使用#define是不受欢迎的,因为它可能导致冲突.常量是8位或16位的十六进制模式,存储为uint8_t或uint16_t.这些常量也不会从类的实例更改为实例,因此只需要一个常量副本就可以保存内存(尽管内存非常少).
是否存在任何不正确的,或者更好的方式来实现上述内容,而不是简单地执行以下操作:
// mycode.h
// .......
class myclass {
private:
static const uint16_t kMyClassConstant_ = 0xBEEF;
// .......
};
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助.
考虑以下示例(godbolt):
#include <iostream>
template <typename T>
const T *as_const(T *p) { return p; }
void f() {}
template <typename T>
void g(T *) { std::cout << "A"; }
template <typename T>
void g(const T *) { std::cout << "B"; }
int main() {
g(as_const(&f));
}
Run Code Online (Sandbox Code Playgroud)
GCC和Clang都可以编译它,但生成的可执行文件产生不同的输出:用GCC打印编译的版本A和用Clang打印编译的版本B.
你能解释一下这个区别吗?
更新:正如@VTT指出的那样,即使as_const被删除也会观察到相同的差异.
我已经看到很多使用const关键字放在类中的函数之后,所以我想知道它是什么.我在这里读了一下:http://duramecho.com/ComputerInformation/WhyHowCppConst.html.
它表示使用const是因为函数"可以尝试改变对象中的任何成员变量".如果这是真的,那么它应该在任何地方使用,因为我不希望以任何方式改变或改变任何成员变量.
class Class2
{ void Method1() const;
int MemberVariable1;}
Run Code Online (Sandbox Code Playgroud)
那么,const的真正定义和用途是什么?
可能重复:
卖给我关于const的正确性
关键字的用处是什么const,C或者C++因为它允许这样的事情?
void const_is_a_lie(const int* n)
{
*((int*) n) = 0;
}
int main()
{
int n = 1;
const_is_a_lie(&n);
printf("%d", n);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:0
很明显,const不能保证论证的不可修改性.
在http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/中,它提到"最重要的const",其中C++故意指定绑定临时对象在堆栈上引用const会延长临时生命周期到引用本身的生命周期.我想知道为什么c ++只允许在引用为const时延长对象的生命周期而不是在不引用时延长对象的生命周期?这个特征背后的理性是什么?为什么它必须是const?
class C
{
public:
void foo() const {}
private:
void foo() {}
};
int main()
{
C c;
c.foo();
}
Run Code Online (Sandbox Code Playgroud)
MSVC 2013不喜欢这样:
> error C2248: 'C::foo' : cannot access private member declared in class 'C'
Run Code Online (Sandbox Code Playgroud)
如果我转向const参考,它的工作原理:
const_cast<C const &>(c).foo();
Run Code Online (Sandbox Code Playgroud)
为什么我不能const在非const对象上调用该方法?
为什么允许在C++中编译以下内容?
#include<iostream>
using namespace std;
class mytest
{
public:
operator int()
{
return 10;
}
operator const int()
{
return 5;
}
};
int main()
{
mytest mt;
//int x = mt; //ERROR ambigious
//const int x = mt; //ERROR ambigious
}
Run Code Online (Sandbox Code Playgroud)
为什么允许转换运算符的不同版本(基于constness)在它们的使用总是导致歧义时进行编译是有意义的?
有人可以澄清我在这里缺少的东西吗?