Passing variables by reference and construct new objects

后端 未结 2 2001
感情败类
感情败类 2021-01-26 13:19

Hello there i have code like this one below and i don\'t know why it doesn\'t work.

class Clazz2;
class Clazz
{
    public:
    void smth(Clazz2& c)
    {

          


        
相关标签:
2条回答
  • 2021-01-26 13:55

    This is because non-constant references are not allowed to bind to temporary objects. References to const, on the other hand, can bind to temporary objects (see 8.3.5/5 of the C++11 Standard).

    0 讨论(0)
  • 2021-01-26 14:06

    Your first smth2 takes a reference, which cannot be bound to a temporary like your constructor call a.smth(Claszz2()). However, a const reference can be bound to a temporary because we cannot modify the temporary, so it is allowed.

    In C++11, you can use an rvalue-refrerence so that you have the ability to bind temporaries as well:

    void smth2(Clazz2 &&);
    
    int main()
    {
        a.smth(Claszz2()); // calls the rvalue overload
    }
    
    0 讨论(0)
提交回复
热议问题