const的目的是什么?
const Object myFunc(){
return myObject;
}
Run Code Online (Sandbox Code Playgroud)
我刚刚开始阅读Effective C++,而第3项提倡这一点,Google搜索也提出了类似的建议,但也有反作用.我看不出在这里使用const会更好.假设需要按值返回,我认为没有任何理由保护返回的值.给出为什么这可能有用的示例是防止返回值的意外bool强制转换.实际问题是应该使用explicit关键字来防止隐式bool强制转换.
在这里使用const可以防止在没有赋值的情 所以我无法用这些对象执行算术表达式.似乎没有一个未命名的const有用的情况.
在这里使用const获得了什么,何时更可取?
编辑:将算术示例更改为修改在分配之前可能要执行的对象的任何函数.
在Effective C++第03项中,尽可能使用const.
class Bigint
{
int _data[MAXLEN];
//...
public:
int& operator[](const int index) { return _data[index]; }
const int operator[](const int index) const { return _data[index]; }
//...
};
Run Code Online (Sandbox Code Playgroud)
const int operator[]确实有所作为int& operator[].
但是关于:
int foo() { }
Run Code Online (Sandbox Code Playgroud)
和
const int foo() { }
Run Code Online (Sandbox Code Playgroud)
似乎他们是一样的.
我的问题是,为什么我们用const int operator[](const int index) const而不是int operator[](const int index) const?
我正在学习C++,我仍然对此感到困惑.在C++中将值作为常量,引用和常量引用返回有什么含义?例如:
const int exampleOne();
int& exampleTwo();
const int& exampleThree();
Run Code Online (Sandbox Code Playgroud) 假设我有这个功能
#include <string>
std::string const foo()
{
std::string s = "bar";
return s;
}
int main()
{
std::string t = foo();
}
Run Code Online (Sandbox Code Playgroud)
编译器是否可以执行(命名)返回值优化t,即使由于-ness差异的类型s和t返回类型不同?fooconst
(如果C++ 03和C++ 11的答案不同,那么我肯定对了解C++ 03答案感兴趣.)
我应该更喜欢堆分配到堆分配.传递值更好(特别是如果你正在创建新对象 - 但同时,如果你通过基类返回,你的对象将被切片),或者至少通过引用而不是传递指针(尽管你不能创建引用向量).
我仔细阅读了所有这些内容,现在我觉得我对之前所了解的知之甚少.关于如何编写一个IMO应该是微不足道的代码,我并没有丝毫想法,同时尊重所有这些精心编写和思考的答案中提到的最佳实践.
这是我想要实现的.(我不假装它是正确的C++,但我只是想传达这个想法).
// This thing is purely virtual!
class BaseStuff { }
// Has important behaviour and data members that shouldn't be sliced
class SomeStuff : public BaseStuff { }
// Don't slice me plz
class OtherStuff : public BaseStuff { }
BaseStuff CreateStuff()
{
// falls a set of rules to create SomeStuff or OtherStuff instance based on phase of the moon
}
std::vector<BaseStuff> CreateListOfStuff()
{ …Run Code Online (Sandbox Code Playgroud) 说我有这个功能:
template <class A>
inline A f()
{
A const r(/* a very complex and expensive construction */);
return r;
}
Run Code Online (Sandbox Code Playgroud)
声明是不是一个好主意r const,因为const变量无法移动?请注意,返回的值不是const.我正在努力解决的问题是,r确实如此const,但这样做可能不是一个好主意.然而,限定符应该是帮助编译器生成更好的代码.