我有这个示例代码:
struct A
{
bool test() const
{
return false;
}
};
template <typename T = A>
class Test
{
public:
Test(const T& t = T()) : t_(t){}
void f()
{
if(t_.test())
{
//Do something
}
}
private:
const T& t_;
};
int main()
{
Test<> a;
a.f();
}
Run Code Online (Sandbox Code Playgroud)
基本上我担心Test我将const引用存储到临时变量并在methof中使用它的构造函数f.临时对象引用在内部f是否仍然有效?
我想知道我是否正在使用以下的好方法:
下面的代码似乎有效,但我想知道我是否只是"幸运"编译器足够同情.
为清楚起见,我在下面的评论中添加了评论和我的问题.
谢谢 !
struct Foo
{
std::string mValue;
};
class B
{
public:
B(const Foo & foo) : mFoo_External(foo) {}
private:
const Foo & mFoo_External; //this is an external reference to the member
//(coming from A)
};
class A
{
public:
//Here is the big question
//Shall I use :
// A(const Foo & foo) : mFoo(foo), mB(mFoo) {}
// or the declaration below
A(const Foo & foo) : mFoo(foo), mB(foo) {}
private:
//According to my …Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
#include <iostream>
using namespace std;
class A {
private:
int x;
public:
int& get_ref() {
cerr << "non const" << endl;
return x;
}
const int& get_ref() const {
cerr << "const" << endl;
return x;
}
};
int main () {
A a;
a.get_ref() = 10;
cout << a.get_ref() << endl;
const int& y = a.get_ref();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我希望第二次和第三次调用a.get_ref()运行第二版get_ref()方法(并输出const标准错误).但看起来总是第一个版本被调用.如何实现两个不同的'getter'并确保根据上下文调用正确的版本?即,至少在第三次通话时
const int& y = a.get_ref();
Run Code Online (Sandbox Code Playgroud)
第二个版本执行?(一个不优雅的解决方案是使用不同的名称,例如get_ref,get_const_ref但我试图看看是否可以避免.)
为什么引用无法捕获临时值,而const引用和右值引用可以捕获并延长对象的生命周期.换句话说,虽然两个第一行是合法的但第三行不是:
const string &a = string("a");
string &&b = string("b");
string &c = string("c"); // why illegal?
Run Code Online (Sandbox Code Playgroud) 我有一些关于重新获取类成员变量的引用的问题。
我有以下代码:
#include <stdint.h>
#include <string>
#include <iostream>
#include <set>
void
PrintSet (const std::string & str, const std::set<uint32_t> & to_print)
{
std::cout << str << " (" << to_print.size () << "): ";
for (std::set<uint32_t>::const_iterator it = to_print.begin ();
it != to_print.end (); ++it)
{
std::cout << *it << " ";
}
std::cout << "\n";
}
class Test
{
private:
std::set<uint32_t> m_values;
public:
Test () : m_values () { }
void
SetValues (const std::set<uint32_t> & values)
{
m_values = values; …Run Code Online (Sandbox Code Playgroud) 我正在使用C++和const引用,并且很困惑为什么这段代码有效:
#include <iostream>
class A {
public:
A() : a_(50) {}
const int& getA() const { return a_; }
private:
const int a_;
};
int main(int argc, char* argv[])
{
A* a = new A();
const int& var = a->getA();
std::cout << var << std::endl;
delete a;
std::cout << var << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
结果:
50
50
Run Code Online (Sandbox Code Playgroud)
这是我的想法:
var存储对a_的引用.
删除a时,也应删除a_.
当再次访问var时,它不再包含有效的引用,并且应该发生分段错误.
为什么这样做?我不相信我是临时副本.
我有以下模板类,其中成员是const ref类型。对象的复制被禁用,并且只需要移动对象和移动赋值运算符。
Q1:如何const ref type正确实现移动赋值运算符(我所做的是否正确)?
Q2:为什么会这样
MyClass<int> obj2(std::move(obj)); // will work with move ctor
MyClass<int> obj3 = std::move(obj2); // also move ctor called: Why?
Run Code Online (Sandbox Code Playgroud)
发生了?
Q3:在main()移动实例中是否可以调用using print()。是UB吗?
我正在使用Visual Studio 2015 (v140)。这是我的代码:
#include <utility>
#include <iostream>
template<typename Type>
class MyClass
{
const Type& m_ref; // const ref type
public:
explicit MyClass(const Type& arg): m_ref(std::move(arg)){}
// coping is not allowed
MyClass(const MyClass&) = delete;
MyClass& operator=(const MyClass&) = delete;
// …Run Code Online (Sandbox Code Playgroud) 在C++中,可以const &改变的价值吗?
好吧,当然不能改变,可以吗?这const意味着什么.而且,听听Stroustrup:
甲
const左值参考指的是恒定的,这是从视角的参照的用户的点不可变的.
但是这个怎么样?
#include <iostream>
int main() {
int a = 0;
const int& r = a;
const int old_r = r;
++a;
const int new_r = r;
std::cout
<< "old_r == " << old_r
<< " but new_r == " << new_r << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我的机器上,这输出,old_r == 0 but new_r == 1.
这是我真正的问题.在上面的代码中,查看该行
const int new_r = r;
Run Code Online (Sandbox Code Playgroud)
只要
&new_r既不在此行也不在代码的其他地方提取volatile,没有任何东西阻止优化编译器从合并old_r …
这是一个说明我的问题的代码片段:
class A {...};
const A& foo1() {...}
const A& foo2() {...}
void foo3(int score) {
if (score > 5)
const A &reward = foo1();
else
const A &reward = foo2();
...
// The 'reward' object is undefined here as it's scope ends within the respective if and else blocks.
}
Run Code Online (Sandbox Code Playgroud)
如何在 if else 块之后访问reward对象foo3()?这是避免代码重复所必需的。
提前致谢 !
_numbers我执行了以下操作,作为允许通过以下方式对成员容器进行只读访问的廉价方法numbers:
class Foo {
Foo() : _numbers({}), numbers(_numbers) {
// some code that populates `numbers` via `numbers.push_back(...)`
}
private:
std::vector<int> _numbers;
public:
const std::vector<int>& numbers;
}
Run Code Online (Sandbox Code Playgroud)
然而,这样做我发现它numbers是空的,而在其他情况下它将包含与 相同的元素_numbers。
更准确地说,这似乎是未定义的行为。在我的真实示例(这是一个简化版本)中,我有多个采用此方案的引用容器对,其中填充的数据在某些对的常量引用成员中可见,而对于某些对则不可见。
知道这有什么问题吗?非常感谢任何帮助。
编辑这是一个最小的工作示例:
#include <vector>
struct Foo2 {
public:
const int max1;
const int center1;
Foo2(const int max1_);
private:
std::vector<int> _numbers1, _numbers2;
public:
const std::vector<int>& numbers1, numbers2;
};
Foo2::Foo2(const int max1_)
: max1(max1_), center1(max1_/2),
_numbers1({}), _numbers2({}),
numbers1(_numbers1),
numbers2(_numbers2)
{
cout << max1 …Run Code Online (Sandbox Code Playgroud) 有一个简单的程序
#include <stdio.h>
int counter = 3;
const int& f() {
return counter++;
}
const int& g() {
return counter++;
}
const int& h(int w) {
counter = w;
return counter;
}
void main()
{
const int& x = f();
const int& y = g();
const int& z = g();
const int& t = h(123);
counter = 45678;
printf("%d %d %d %d", x, y, z, t);
}
Run Code Online (Sandbox Code Playgroud)
为什么它的输出是5 5 5 45678?特别是,为什么x和y是5?如果初始化后它们仍然连接到计数器,为什么它们不是 45679 或类似的东西?
c++ ×11
const-reference ×11
reference ×5
const ×2
c++11 ×1
overloading ×1
polymorphism ×1
return ×1
scope ×1