标签: const-reference

这个有效的C++代码是否符合标准?

我有这个示例代码:

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是否仍然有效?

c++ scope reference const-reference

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

C++:const引用和初始化顺序

我想知道我是否正在使用以下的好方法:

  • 我想构造一个父类(类A),这个类应该拥有给定"Foo"类的实例
  • 我希望父类拥有子类成员(类B),并且该成员应该具有对父类的foo成员的引用.

下面的代码似乎有效,但我想知道我是否只是"幸运"编译器足够同情.

为清楚起见,我在下面的评论中添加了评论和我的问题.

谢谢 !

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)

c++ const-reference

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

为什么不调用带有const引用返回值的重载方法?

考虑以下代码:

#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但我试图看看是否可以避免.)

c++ polymorphism overloading reference const-reference

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

为什么引用无法捕获临时而const ref和rval ref可以

为什么引用无法捕获临时值,而const引用和右值引用可以捕获并延长对象的生命周期.换句话说,虽然两个第一行是合法的但第三行不是:

const string &a = string("a");
string &&b = string("b");
string &c = string("c"); // why illegal?
Run Code Online (Sandbox Code Playgroud)

c++ reference rvalue-reference const-reference

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

C++ 通过引用返回和通过常量引用返回值被复制

我有一些关于重新获取类成员变量的引用的问题。

我有以下代码:

#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++ return reference const-reference return-by-reference

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

为什么这样做?在C++中返回const引用

我正在使用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时,它不再包含有效的引用,并且应该发生分段错误.

为什么这样做?我不相信我是临时副本.

c++ const const-reference

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

如何为模板类的 const ref 成员定义移动赋值运算符

我有以下模板类,其中成员是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++ language-lawyer const-reference move-semantics c++11

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

const&指的是非易失性变量.变量发生了变化.更改是否使const&?无效?

在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 …

c++ const reference undefined-behavior const-reference

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

C++中const引用对象的条件赋值

这是一个说明我的问题的代码片段:

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()?这是避免代码重复所必需的。

提前致谢 !

c++ ternary-operator const-reference

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

如何在 C++ 初始化列表中将 const 引用成员初始化为另一个成员(std 向量)

_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)

c++ initialization initializer-list const-reference

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

const 引用指的是哪里?

有一个简单的程序

#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++ const-reference

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