c++ - 右值引用未定义行为

标签 c++

#include<iostream>

struct Test
{
    int n ;
    ~Test(){}

    Test& operator =(int v)
    {
        n=v;
        return *this;
    }
};

Test * ptr = nullptr;

void g(Test && p)
{
    std::cout << "&&";
}


void g(Test & p)
{
    ptr = &p;
    std::cout << "&";
}

void f(Test&& t)
{
    g(t);
}

void buggy()
{
    *ptr  = 5;
}

int main()
{ 
    f(Test());
    buggy();
    std::cin.ignore(); 
} 

可以肯定的是,当我们保留临时地址时,上面的代码会导致未定义的行为?

最佳答案

声明指向结构Test* ptr; 的指针或您所说的“保持地址” 不会导致未定义的行为。使用指向生命周期结束的对象的指针。

main 中由 Test() 创建的对象的生命周期在 f(Test()); 执行后立即结束。在那之后,无论你使用 ptr 做什么都是未定义的。即使在其生命周期结束后,该对象很可能仍保留在内存中,但您不应该依赖它。

您还应该查看:What are all the common undefined behaviours that a C++ programmer should know about?

关于c++ - 右值引用未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9349148/

相关文章:

c++ - TCA9548a(I2C 多路复用器)C++ 集成

c++ - 如何从circular_buffer中获取元素

c++ - 在 C++ 中轮询原子变量(bool)?

c++ - OpenCL 内核因特定参数而崩溃

C++/生成文件错误 : undefined reference to `main'

c++ - 如何在 C++ 中实现类似 for_each 的函数?

c++ - 矩阵乘法速度问题

c++ - thrift 中的 Union 显示 c++ 中设置的所有值

c++ - SendInput() 不等于在 C++ 键盘上手动按键?

c++ - 好或坏 : to make giant struct to avoid using globals/properties of a struct/lots of paramerters