相关疑难解决方法(0)

为什么非const引用不能绑定到临时对象?

为什么不允许对一个临时对象进行非const引用,哪个函数getx()返回?显然,这是C++标准禁止的,但我对这种限制的目的感兴趣,而不是对标准的引用.

struct X
{
    X& ref() { return *this; }
};

X getx() { return X();}

void g(X & x) {}    

int f()
{
    const X& x = getx(); // OK
    X& x = getx(); // error
    X& x = getx().ref(); // OK
    g(getx()); //error
    g(getx().ref()); //OK
    return 0;
}
Run Code Online (Sandbox Code Playgroud)
  1. 很明显,对象的生命周期不是原因,因为C++标准不禁止对对象的持续引用.
  2. 很明显,上面的示例中的临时对象不是常量,因为允许调用非常量函数.例如,ref()可以修改临时对象.
  3. 此外,ref()允许您欺骗编译器并获取此临时对象的链接,这解决了我们的问题.

此外:

他们说"为const引用分配一个临时对象可以延长这个对象的生命周期","但是对于非const引用却没有任何说法".我的其他问题.以下赋值是否延长了临时对象的生命周期?

X& x = getx().ref(); // OK
Run Code Online (Sandbox Code Playgroud)

c++ const reference temporary c++-faq

221
推荐指数
6
解决办法
9万
查看次数

如何允许将C++ 98 API的临时值转换为l值

我有C++ 98 API,通过非const 引用获取值并更改此值.
具体而言,我使用的OpenCV和功能是cv::rectangle(),这需要cv::Mat &在要被绘制的图像.

同样的API也使用表达式模板来优化图像算术.我可以通过创建表示子图像的(非常量)临时包装对象在感兴趣区域(ROI)上绘制一个矩形.

有了VS2010,我可以写:

cv::Mat a(10,10,CV_8UC1); // create 10x10 image
Rect rec(0,0,2,2);        // create 2x2 rectangle
cv::rectangle(a, rec, cv::Scalar::all(0));      // (1) draw 2x2 on full image
cv::rectangle(a(rec), rec, cv::Scalar::all(0)); // (2) draw 2x2 on 2x2 sub-image << !!!
Run Code Online (Sandbox Code Playgroud)

这没有问题.在第(2)行,创建临时子图像包装器对象并通过cv::rectangle引用传递给它.

但是,在支持C++ 11的 Clang的XCode for iOS上,第(2)行会出现以下错误:

.../test.cpp:605:5: No matching function for call to 'rectangle'
.../core.hpp:2594:17: Candidate function not viable: expects an l-value for 1st argument 
Run Code Online (Sandbox Code Playgroud)

为了完整起见,这是相关的原型:

//! draws the rectangle …
Run Code Online (Sandbox Code Playgroud)

opencv clang lvalue ios c++11

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

标签 统计

c++ ×1

c++-faq ×1

c++11 ×1

clang ×1

const ×1

ios ×1

lvalue ×1

opencv ×1

reference ×1

temporary ×1